本文介绍了NextSibling如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道的工作方式如果使用方法?
这是显示问题的代码示例:

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

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 我希望得到第二个元素:

So, after the very first NextSibling I expected to get on the second element:

< div class = secondClass>

但是出于未知的原因,您需要调用双 NextSibling 从第一个元素移到第二个元素。
正如您在第一个 NextSibling 之后看到的那样,对象的 TypeName Text 。但是我实际上看不到任何文本...

<div class="secondClass">But for uknown reasons you need to call double NextSibling to move from the first element to the second one.And as you can see after the first NextSibling the TypeName of the object is Text. But I don't see any text actually...

请您解释一下为什么我们需要使用两个 NextSibling 和什么是 Text 对象在使用第一个 NextSibling 后得到了?

Could you please explain why we need using two NextSibling and what's the Text object is getting after using the first NextSibling?

推荐答案

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

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

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.

比较:

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

另请参见。

这篇关于NextSibling如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 11:17