I\'m wondering how property NextSibling works in case of using method getElementsByClassName() ? Here is an code example showing the problem:
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.
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.