Hi everybody, I'm new to JavaScript and I'm having a small problem that I can't figure out. I have a the following html which is basically a list with a line to launch a JavaScript function :and I have the following JavaScript code I'm using for testing purposes only as I'm new to JavaScript (I'm trying to understand a code I found on the internet) :HTML Code:<p onClick=test()>test<p> <div class="sidebarmenu"> <ul id="sidebarmenu1"> <li><a href="#">Item 1</a></li> <li><a href="#">Item 2</a></li> <li><a href="#">Folder 1</a> <ul> <li><a href="#">Sub Item 1.1</a></li> <li><a href="#">Sub Item 1.2</a></li> </ul> </li> <li><a href="#">Item 3</a></li> <li><a href="#">Folder 2</a> <ul> <li><a href="#">Sub Item 2.1</a></li> <li><a href="#">Folder 2.1</a> <ul> <li><a href="#">Sub Item 2.1.1</a></li> <li><a href="#">Sub Item 2.1.2</a></li> <li><a href="#">Sub Item 2.1.3</a></li> <li><a href="#">Sub Item 2.1.4</a></li> </ul> </li> </ul> </li> <li><a href="#">Item 4</a></li> </ul> </div>Well, if put in this way, as soon as I launch the page, I get an alert box with "hello" and if I click the test link in html it launches the test function and I get an alert box with the text "[object HTML collection]".Code:var menuids=["sidebarmenu1"]; function test(){ var ultags=document.getElementById(menuids[0]).getElementsByTagName("ul"); alert(ultags); } alert("hello");
Well, all this looks fine.
Now what I did is get the variable assignment to ultags outside the function (trying to make ultags a global variable)
And when I launch the page nothing happens, I don't get an alert box with the text "hello" and when I click the test link in html, an alert box shows displaying "undefined". What I want to know is why the "hello" alert box isn't showing anymore and why the variable ultags is undefined ?Code:var menuids=["sidebarmenu1"]; var ultags=document.getElementById(menuids[0]).getElementsByTagName("ul"); function test(){ alert(ultags); } alert("hello");
However, if I replacewithCode:var ultags=document.getElementById(menuids[0]).getElementsByTagName("ul");the "hello" box shows, and when I click the test link, I get an alert box with the text "null".Code:var ultags=document.getElementById(menuids[0]);
In the other hand, when I replacewithCode:var ultags=document.getElementById(menuids[0]).getElementsByTagName("ul");the "hello box shows, and when I click the test link, I get an alert box with the text "[object HTML collection]".Code:var ultags=document.getElementsByTagName("ul");
So please, what is going on ?
I also have another question, I used the first code and added a line within the javascript tags to execute the function like this
When I launch the page, the function doesn't launch, why is that ?Code:var menuids=["sidebarmenu1"]; function test(){ var ultags=document.getElementById(menuids[0]).getElementsByTagName("ul"); alert(ultags); } test();
Adding the same line to html displayed it as plain text, why is that ?


Reply With Quote
Bookmarks