Node.nextSibling 是一個(gè)只讀屬性,返回其父節(jié)點(diǎn)的 childNodes 列表中緊跟在其后面的節(jié)點(diǎn),如果指定的節(jié)點(diǎn)為最后一個(gè)節(jié)點(diǎn),則返回 null。
Element.nextElementSibling返回當(dāng)前元素在其父元素的子元素節(jié)點(diǎn)中的后一個(gè)元素節(jié)點(diǎn),如果該元素已經(jīng)是最后一個(gè)元素節(jié)點(diǎn),則返回null,該屬性是只讀的。(IE、Safari不支持)
使用Node.nextSibling時(shí) 可能會(huì)返回預(yù)想節(jié)點(diǎn)之間的回車。
需要判斷Node.nextSibling是否為自己想要的節(jié)點(diǎn)。
node.nodetype
image.png
讓IE/Safari支持Node.nextSibling
// Source: https://github.com/jserz/js_piece/blob/master/DOM/NonDocumentTypeChildNode/nextElementSibling/nextElementSibling.md
(function (arr) {
arr.forEach(function (item) {
if (item.hasOwnProperty('nextElementSibling')) {
return;
}
Object.defineProperty(item, 'nextElementSibling', {
configurable: true,
enumerable: true,
get: function () {
var el = this;
while (el = el.nextSibling) {
if (el.nodeType === 1) {
return el;
}
}
return null;
},
set: undefined
});
});
})([Element.prototype, CharacterData.prototype]);