How does NextSibling work?

前端 未结 2 1320
感动是毒
感动是毒 2021-01-28 16:42

I\'m wondering how property NextSibling works in case of using method getElementsByClassName() ? Here is an code example showing the problem:

2条回答
  •  执笔经年
    2021-01-28 16:56

    As nextSibling returns the next Node object (even a space or a line feed),
    you must want to use nextElementSibling instead.

    See this question for details:
    Whats the difference between nextElementSibling vs nextSibling

    And here is a working snippet:

    (function Sibling() {
      var x = document.getElementsByClassName('firstClass')[0];
      document.getElementById("out1").innerHTML = 'Current: ' + x.className + '. TypeName of the object is  ' + x.constructor.name + '';
      x = x.nextElementSibling;
      document.getElementById("out2").innerHTML = 'Next 1  : ' + x.className + '. TypeName of the object is  ' + x.constructor.name + '';
      x = x.nextElementSibling;
      document.getElementById("out3").innerHTML = 'Next 2  : ' + x.className + '. TypeName of the object is  ' + x.constructor.name + '';
    })()

    Hope it helps.

提交回复
热议问题