Forum Moderators: open

Message Too Old, No Replies

.nextSibling and 'phantom' textNodes

Little function to *not* crash IE

         

whoisgregg

1:29 am on Nov 5, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Was causing IE to crash with a .nextSibling.className call that was inadvertently referencing a non-existent text Node. (Previously referred to by Bernard Marx as 'phantom' text nodes [webmasterworld.com].)

Wrote a function to return a real nextSibling, thought I'd post it here in case others have similar headaches.

function getNextSibling(el) {
el = el.nextSibling;
while (el.nodeType!=1) {
el = el.nextSibling;
}
return el;
}

Usage: (returns [object UL])

<p onclick="alert(getNextSibling(this))">Testing</p>

<ul>
<li></li>
</ul>

Bernard Marx

2:20 am on Nov 5, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Ah, how the past comes back to haunt us.

I think you might be reaching for the paracetamols with that one too, I'm afraid.
It doesn't check to see if there is a nextSibling, so it errors if you use the last element as input.

Try this one:


<script>
function getNextSibling(el)
{
while((el=el.nextSibling) && el.nodeType!=1);
return el;
}

function test(el)
{
var next = getNextSibling(el);
if(next) next.style.backgroundColor = 'blue';
else alert('no nextSibling');
}

</script>

<ul>
<li onclick="test(this);">some text</li>
<li onclick="test(this);">some text</li>
<li onclick="test(this);">some text</li>
<li onclick="test(this);">some text</li>
</ul>

whoisgregg

5:35 pm on Nov 7, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Always more to learn, thank you. :)