Node.nextSibling和Element.nextElementSibling

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]);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。