2

I'm trying to create an array of <li> that are in a div. So I have

var arr = document.getElementById('mainNav').getElementsByTagName('li');

For testing purposes, I put an alert("test"); alert(arr.length); to see if an alert will pop up and what the size of the array is. Neither of the alerts showed up, but if I place an alert before that variable declaration, it works fine. What could be going wrong?

3
  • Any html you could give would help. Commented Feb 8, 2010 at 23:25
  • 1
    If neither of your alerts are showing up, looks mostly like you have an error in another place (or maybe getElementById is returning null), try to debug your script, I would recommend Firebug, just open the Console and load your page, you will see the error messages... Commented Feb 8, 2010 at 23:26
  • yes. it is returning null. how can I fix this problem? Commented Feb 8, 2010 at 23:28

2 Answers 2

2

Perhaps your alerts aren't showing up because document.getElementById('mainNav') is returning null. Check if you're getting a Javascript error. Or break up your code into multiple lines to make it easier to see where the error is occuring:

var mainNav = document.getElementById('mainNav');
alert(mainNav);
var arr = mainNav.getElementsByTagName('li');
Sign up to request clarification or add additional context in comments.

5 Comments

Make sure that you have an element with that particular id in your document.
It will also return null if you are calling it before the page has loaded. If you move this script to the end of the body tag do you still get null?
I do. I have a div... <div id="mainNav"> ... and inside it is the set of list items. Could the problem be that I'm calling another file. <div id="mainNav"> <ORPR:MainNav runat="server" id="nav1" /> </div>
ahhh Thanks! It worked when I moved it to the end of the page. Is there a way I can have this work by not having it at the end of the page?
put in in a function that is called on load . If you use jquery it is document.ready(function(){ /*your code here */ }); in Mootools it is window.addEvent('domready',function(){ /* your code here */ }); with just plain javascript it would be window.onload = function(){ /* your code here */ };
0

If you are sure that you have the LI elements within "mainNav". Try to put your code in the onLoad function:

window.onload = function(){
var arr = document.getElementById('mainNav').getElementsByTagName('li');

}

Your code maybe executing before the element is created.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.