Portability of nextElementSibling/nextSibling

天涯浪子 提交于 2019-11-27 14:37:04

nextSibling will see HTML code comments, so be sure to keep them out.

Other than that you should be alright since you won't have any text nodes between your tr elements.

The only other issue I could think of would be in Firefox 3 where nextElementSibling hadn't yet been implemented. So if you're supporting that browser, you'll need to manually emulate nextElementSibling. (Pretty sure they had it implemented in FF3.5 though.)

You'll be safer to create a nextElementSibling() function:

tr = tr.nextElementSibling || nextElementSibling(tr);

function nextElementSibling( el ) {
    do { el = el.nextSibling } while ( el && el.nodeType !== 1 );
    return el;
}

Considering previous answers, I am currently implementing it this way to grant cross-browser compatibilty:

function nextElementSibling(el) {
    if (el.nextElementSibling) return el.nextElementSibling;
    do { el = el.nextSibling } while (el && el.nodeType !== 1);
    return el;
}

This way, I can avoid the do/while loop for browsers that support nextElementSibling. Maybe I'm too scared of WHILE loops in JS :)

One advantage of this solution is recursability:

//this will always works:
var e = nextElementSibling(nextElementSibling(this));

//this will crash on IE, as looking for a property of an undefined obj:
var e = this.nextElementSibling.nextElementSibling || nextElementSibling(nextElementSibling(this));

Firefox nextSibling returns whitespace \n while Internet Explorer does not.

Before nextElementSibling was introduced, we had to do something like this:

var element2 = document.getElementById("xxx").nextSibling;
while (element2.nodeType !=1)
{
          element2 = element2.nextSibling;
} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!