Как работает NextSibling? - PullRequest
0 голосов
/ 11 мая 2018

Мне интересно, как работает свойство NextSibling в случае использования метода getElementsByClassName () ?Вот пример кода, показывающий проблему:

function Sibling() {
    var x = document.getElementsByClassName('firstClass')[0];
    document.getElementById("out1").innerHTML = 'We are on <b> ' + x.className + '</b>. TypeName of the object is <i> ' + x.constructor.name + '</i>';
    x = x.nextSibling;
    document.getElementById("out2").innerHTML = 'After SINGLE nextSibling we are on <b> ' + x.className + '</b>. TypeName of the object is <i> ' + x.constructor.name + '</i>. WHY IS THAT???!!!';
    x = x.nextSibling;
    document.getElementById("out3").innerHTML = 'After DOUBLE nextSibling we are on <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 onclick="Sibling()">ClickMeAndThenExplainTheResults</button>
</div>

<p id="out1"></p> 
<p id="out2"></p> 
<p id="out3"></p> 

Итак, после самого первого NextSibling я ожидал попасть на второй элемент:

<div class="secondClass"> Нопо неизвестным причинам вам нужно вызвать double NextSibling , чтобы перейти от первого элемента ко второму.И как вы можете видеть после первого NextSibling TypeName объекта равно Text .Но на самом деле я не вижу никакого текста ...

Не могли бы вы объяснить, почему нам нужно использовать два NextSibling и что получает объект Text после использованияfirst NextSibling ?

Ответы [ 2 ]

0 голосов
/ 11 мая 2018

Поскольку nextSibling возвращает следующий объект Node (даже пробел или перевод строки),
вместо этого необходимо использовать nextElementSibling.

Подробности см. В этом вопросе:
В чем разница между nextElementSibling и nextSibling

А вот рабочий фрагмент:

(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>

Надеюсь, это поможет.

0 голосов
/ 11 мая 2018

nextSibling получает следующий узел , а не следующий узел, который является элементом .

Между двумя узлами элемента div есть текстовый узел, содержащий пробелы (пробелы, символы табуляции и новые строки - это текст), и это то, что вы получаете.

Сравните:

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

См. Также nextElementSibling.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...