如何在JavaScript中选中紧随特定元素之后的目标元素?
如何在JavaScript中选中紧随特定元素之后的目标元素?
嗨,我懂你的需求啦——你想实现CSS里相邻兄弟选择器(+)在JavaScript里的效果对吧?你用closest肯定行不通,因为这个方法是向上查找当前元素的祖先节点的,和你要找的“下一个兄弟元素”方向完全相反~
给你两个适配场景的简单解决方案:
方法1:直接用nextElementSibling(最贴合CSS +的效果)
这个属性会返回当前元素的下一个元素节点(自动跳过文本、注释这类非元素节点),完美对应CSS里A + B的逻辑——也就是选中紧跟在A后面的第一个B元素。
针对你的代码,只需要把错误的closest部分替换成这个属性就行,另外注意你原来写的'input.innerHTML'是字符串,应该改成实际获取input的内容:
<div class="input" style="display: none"> foo </div> <div class="output"></div> <div class="input" style="display: none"> foo </div> <div class="output"></div> <script> 'use strict'; window.onload = function() { for (const input of document.querySelectorAll('.input')) { // 获取紧跟当前input的下一个元素 const targetOutput = input.nextElementSibling; // 把input的内容赋值给对应的output targetOutput.innerHTML = input.innerHTML; } } </script>
方法2:更灵活的匹配(如果需要验证目标元素)
如果你的场景里,下一个兄弟元素不一定是.output,或者需要额外验证选择器,可以用matches()方法配合nextElementSibling做判断:
for (const input of document.querySelectorAll('.input')) { const nextSibling = input.nextElementSibling; // 确认下一个元素是我们要找的.output if (nextSibling && nextSibling.matches('.output')) { nextSibling.innerHTML = input.innerHTML; } }
这样能避免意外选中不符合要求的元素,逻辑更稳健~
备注:内容来源于stack exchange,提问作者jsx97
相关产品推荐
相关产品推荐

