Reputation: 21
This is my code
var menuLi=[];
$(window).load(function() {
var menuUl = document.getElementById("sub");
menuLi = menuUl.getElementsByTagName("LI");
var len = menuUl.childNodes.length;
nSpan = document.createElement("SPAN");
var findUl;
for (var i = 0; i < len; i++) {
findUl = menuLi[i].getElementsByTagName("UL");
liLen = findUl.length;
if (liLen > 0) {
menuLi[i].classList.add("myNew");
}
}
});
The above is my code which throws error menuLi[i] is undefined.
Upvotes: 1
Views: 54
Reputation: 32145
Problem:
In fact you are looping using the wrong length
.
Explanation:
Because the menuLi.length
is lower than menuUl.childNodes.length
, as menuUl.childNodes
will contain all the li
inside menuUl
and their children.
So menuUl.childNodes.length
is the number of li
elements multiplied by the number of elements in each li
.
So i
will get greater than the menuLi.length
, and that explains why you got menuLi[i] is undefined
, because if you have only 5 li
in menuUl
and for example you are trying to get menuLi[8]
, where menuLi[8]
is undefined
.
Solution:
So just use:
var len = menuLi.length;
Upvotes: 1
Reputation: 17952
You are looping from 1
to menuUl.childNodes.length
using i
, but you are indexing straight into menuUl[i]
. Do you mean menuUl.childNodes[i]
?
Upvotes: 0