开发者

create array of <li>s in a specific div using javascript

开发者 https://www.devze.com 2022-12-19 19:21 出处:网络
I\'m trying to create an array of <li> that are in a div. So I have var arr = document.getElementById(\'mainNav\').getElementsByTa开发者_开发问答gName(\'li\');

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

var arr = document.getElementById('mainNav').getElementsByTa开发者_开发问答gName('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?


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');


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消