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

标签 javascript html closest nextsibling

我有两个 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/

相关文章:

jQuery 最接近();

javascript - 在 Rails 中,我发送一个 var 来查看,但在 js 文件中为 nil

javascript - HTML 和 CSS : How to lay out a div tag with width:100% and left:300px

jquery - 使用removeClass ("hidden")显示/隐藏div

javascript - Firefox 中的 `ImportNode` 并从 `iframe` 中提取元素

javascript - closest() 方法没有按预期工作

javascript - jquery 在输入单击时添加类并在单击其他输入时删除类

javascript - 如何在滚动时仅触发元素上的单击事件?

javascript - unpoly加载的fragments中的脚本不执行

javascript - jqGrid 如何将额外的类应用于标题列