How, using vanilla JavaScript can i most efficiently (and elegantly) select all elements between two other specified elements? For example, how could I pick all elements between:
<h2>
and <hr>
.. which would result in an [ p, p, ul ]
... notice the <p>this should not be found</p>
should not be "found" since its there is no
after it.
I know i can write a bunch of JS to check siblings, and iterate through - but im hoping there is a more elegant way im not seeing. I'd be find if there was some querySelectorAll(..) selector machination i could use as well (or like an intersection of 2 invocations) ..
<div>
<h1>Title</h1>
<h2>Subitle</h2>
<p>Para 1 <a href="#">link</a></p>
<p>Para 2</p>
<ul><li>A list</li></ul>
<hr/>
<h2>Another subtitle</h2>
<p>this should not be found</p>
</div>
CodePudding user response:
Here's one solution that utilizes nextElementSibling
:
const getChildrenInRange = (parent, firstChildSelector, lastChildSelector) => {
const res = [];
let current = parent.querySelector(firstChildSelector)?.nextElementSibling;
while (current && !current.matches(lastChildSelector)) {
res.push(current);
current = current.nextElementSibling;
}
return res;
}
const elements = getChildrenInRange(document.getElementById('container'), 'h2', 'hr');
console.log(elements);
<div id="container">
<h1>Title</h1>
<h2>Subitle</h2>
<p>Para 1 <a href="#">link</a></p>
<p>Para 2</p>
<ul><li>A list</li></ul>
<hr/>
<h2>Another subtitle</h2>
<p>this should not be found</p>
</div>
CodePudding user response:
You can use the sibling selectors: h2.nextElementSibling, h2.nextElementSibling.nextElementSibling and hr.previousElementSibling