我有两个 div
元素,第一个 div 中有一个按钮,如下所示。
<div class='my-class'>
<div class='other-div'>
<button onClick="nextDiv(this);">Click</button>
</div>
</div>
<div class='my-class'>
</div>
下面是我的 JavaScript 代码。
function nextDiv(element) {
element.closest('.my-class').style.display = 'none';
element.closest('.my-class').nextSibling.style.display = 'block';
}
为什么我点击按钮时,可以隐藏第一个元素,但不能显示下一个类为my-class
的div元素。相反,我收到以下错误:
Uncaught TypeError: Cannot set property 'display' of undefined
似乎我无法使用 nextSibling 属性选择类 my-class
的下一个 div 元素。我做错了什么?
最佳答案
nextSibling
在这种情况下返回一个文本节点:
<TextNode textContent=" \n">
使用nextElementSibling
相反。
Gecko-based browsers insert text nodes into a document to represent whitespace in the source markup. Therefore a node obtained, for example, using Node.firstChild or Node.previousSibling may refer to a whitespace text node rather than the actual element the author intended to get.
关于javascript - 为什么我不能使用纯 JavaScript 选择下一个 DIV 兄弟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32720190/