gpt4 book ai didi

javascript - 为什么我不能使用纯 JavaScript 选择下一个 DIV 兄弟?

转载 作者:搜寻专家 更新时间:2023-10-31 08:16:46 27 4
gpt4 key购买 nike

我有两个 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相反。

来自 MDN: Node.nextSibling

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com