首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NextSibling是如何工作的?

NextSibling是如何工作的?
EN

Stack Overflow用户
提问于 2018-05-11 12:15:14
回答 2查看 660关注 0票数 0

我想知道属性https://www.w3schools.com/jsref/prop_node_nextsibling.asp在使用()方法时是如何工作的?下面是一个显示问题的代码示例:

代码语言:javascript
复制
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>';;
}
代码语言:javascript
复制
<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是文本。但我没看到任何短信。

请您解释一下为什么我们需要使用两个NextSibling,以及在使用第一个NextSibling之后文本对象得到了什么

EN

回答 2

Stack Overflow用户

发布于 2018-05-11 12:17:10

nextSibling获取下一个节点,而不是一个元素的下一个节点。

在两个div元素节点之间,有一个包含空白的文本节点(空格、制表符和新行是文本),这就是您要得到的。

比较:

代码语言:javascript
复制
1: <div></div> <div></div>
2: <div></div><div></div>

另见nextElementSibling

票数 4
EN

Stack Overflow用户

发布于 2018-05-11 12:27:55

nextSibling返回下一个Node对象(甚至是空格或行提要)时,

您必须使用nextElementSibling代替。

有关详情,请参阅本问题:

Whats the difference between nextElementSibling vs nextSibling

下面是一个有用的片段:

代码语言:javascript
复制
(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>';
})()
代码语言:javascript
复制
<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>

希望能帮上忙。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50292161

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档