Node.nextSibling 是一個只讀屬性,返回其父節點的 childNodes 列表中緊跟在其后面的節點,如果指定的節點為最后一個節點,則返回 null。
Element.nextElementSibling返回當前元素在其父元素的子元素節點中的后一個元素節點,如果該元素已經是最后一個元素節點,則返回null,該屬性是只讀的。(IE、Safari不支持)
使用Node.nextSibling時 可能會返回預想節點之間的回車。
需要判斷Node.nextSibling是否為自己想要的節點。
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]);