【发布时间】:2018-10-21 20:40:29
【问题描述】:
我想知道属性 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 以及在使用第一个 NextSibling 之后 Text 对象会得到什么?
【问题讨论】:
标签: javascript html dom