如何使用原生JavaScript查找两个指定DOM元素之间的元素
原生JavaScript优雅选取两个指定元素间的所有元素
针对你给出的HTML结构,要选取<h2>和紧随其后的<hr>之间的所有元素(即示例中的<p>、<p>、<ul>),同时排除后面没有<hr>的元素,可以用以下几种优雅实现:
方法一:利用现代CSS选择器(推荐,简洁高效)
现代浏览器(Chrome 101+、Firefox 121+等)支持:has()和组合选择器,可以直接用querySelectorAll一次性选中目标元素:
const targetElements = document.querySelectorAll('h2 ~ *:not(hr):has(~ hr)');
选择器解析
h2 ~ *:选中所有在<h2>之后的兄弟元素:not(hr):排除<hr>自身:has(~ hr):只保留后面紧跟<hr>兄弟的元素(自动排除第二个<h2>后的<p>,因为它后面没有<hr>)
如果需要精准匹配第一个<h2>到第一个<hr>之间的元素,可加上父容器限制:
const targetElements = document.querySelector('div').querySelectorAll('h2:first-of-type ~ *:not(hr):has(~ hr)');
方法二:兼容旧浏览器的优雅遍历写法
如果需要兼容不支持:has()的旧浏览器,可用原生DOM API结合数组方法实现,逻辑清晰且代码简洁:
// 定位起始和结束元素 const startEl = document.querySelector('h2'); const endEl = startEl?.nextElementSibling?.closest('hr'); if (startEl && endEl) { const elements = []; let currentEl = startEl.nextElementSibling; // 遍历直到遇到hr while (currentEl && currentEl !== endEl) { elements.push(currentEl); currentEl = currentEl.nextElementSibling; } console.log(elements); // 输出 [p, p, ul] }
也可以用数组方法简化遍历逻辑:
const parent = document.querySelector('div'); const allSiblings = Array.from(parent.children); const startIndex = allSiblings.findIndex(el => el.tagName === 'H2'); const endIndex = allSiblings.findIndex(el => el.tagName === 'HR'); if (startIndex !== -1 && endIndex !== -1 && startIndex < endIndex) { const targetElements = allSiblings.slice(startIndex + 1, endIndex); console.log(targetElements); }
内容的提问来源于stack exchange,提问作者empire29
相关产品推荐
相关产品推荐

