views:

135

answers:

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?

Thanks, Hristo

+2  A: 

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');
Jacob
yes it is returning null... how can I fix this?
Hristo
Make sure that you have an element with that particular id in your document.
Waleed Al-Balooshi
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?
Gordon Tucker
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>
Hristo
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?
Hristo
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 */ };`
Gordon Tucker
A: 

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.

JONYC
yes that was the problem. Thanks
Hristo