Click to See Complete Forum and Search --> : [RESOLVED] Javascript nextSibling


Shawazi
05-27-2007, 03:00 PM
Hello I am running this test:


var myList = document.getElementById('mainList');
var myListI = myList.getElementsByTagName('li');
var myLLength = myListI.length;
for (i=0;i<myLLength;i++) {
if (myListI[i].nextSibling)
alert(myListI[i].id+' is before '+myListI[i].nextSibling.id);
else
alert(myListI[i].id+' is last');
}


It prints:

li0 is before li1
li1 is before undefined
li2 is before li3
li3 is last


li0 and li1 were both on the page onload. li2 and li3 were added later dynamically. For some reason the dynamically added ones can't detect the "static" ones and visa versa.

Shawazi
05-27-2007, 03:26 PM
Also, if I take away .id, it prints:

Object LI
Object LI
Object Text
Object LI

dougal85
05-27-2007, 07:11 PM
can you provide the full page so i can try it? I don't follow fully

Shawazi
05-27-2007, 07:14 PM
The page has a few LIs, but I believe the problem was a whitspace node. I added these line to solve it:


if (nodeObj.previousSibling.id != null) {
var previousSibling = nodeObj.previousSibling.id; //previous sibling ID
}
else {
if(nodeObj.previousSibling.previousSibling != null)
if(nodeObj.previousSibling.previousSibling.id != "")
previousSibling = nodeObj.previousSibling.previousSibling.id; //previous sibling ID
}