How does NextSibling work?

前端 未结 2 1319
感动是毒
感动是毒 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:51

    nextSibling gets the next node and not the next node that is an element.

    Between the two div element nodes, there is a text node containing white space (spaces, tab, and new lines are text) and that is what you are getting.

    Compare:

    1: <div></div> <div></div>
    2: <div></div><div></div>
    

    See also nextElementSibling.

    0 讨论(0)
  • 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: <b>' + x.className + '</b>. TypeName of the object is <i> ' + x.constructor.name + '</i>';
      x = x.nextElementSibling;
      document.getElementById("out2").innerHTML = 'Next 1  : <b>' + x.className + '</b>. TypeName of the object is <i> ' + x.constructor.name + '</i>';
      x = x.nextElementSibling;
      document.getElementById("out3").innerHTML = 'Next 2  : <b>' + x.className + '</b>. TypeName of the object is <i> ' + x.constructor.name + '</i>';
    })()
    <div class="general">
      <div class="firstClass">
      </div>
    
      <div class="secondClass">
      </div>
    
      <button>I do nothing</button>
    </div>
    
    <p id="out1"></p>
    <p id="out2"></p>
    <p id="out3"></p>

    Hope it helps.

    0 讨论(0)
提交回复
热议问题