I have the following example:
https://jsfiddle.net/p5bweLnc/10/
<div class="foo">
<div id="a1" class="bar">
</div>
</div>
<div class="foo">
<div id="a2" class="bar">
</div>
</div>
<div class="foo">
<div id="a3" class="bar">
</div>
</div>
<div class="foo">
<div id="a4" class="bar">
</div>
</div>
<div class="foo">
<div id="a5" class="bar">
</div>
</div>
<div class="foo">
<div id="a6" class="bar">
</div>
</div>
CSS:
.foo {
width: 100px;
height: 100px;
padding: 10px;
background: yellow;
}
.bar {
width: 100%;
height: 100%;
background: green;
}
JS:
let fourth = document.querySelector(`#a4`);
Let’s say I have selected the fourth one using the above JS. Is there a querySelector which lets me grab all the bar
class divs which are BEFORE this fourth one? So a1, a2, a3? Or, is there a way to grab the previous one – a3?
Something like an "upto" selector and from a different parent?
2
Answers
I am not aware of any query selector like that but you can achieve it with this code
Check it out here.
There isn’t a built-in querySelector that I am aware of which directly grabs all the elements before a specific element in the way you mentioned. Having said that, you can achieve your requirement using
js
by iterating through the elements with thebar
class and collecting the ones that come before the selected element.To only grab the previous element (
a3
), you can use thepreviousElementSibling
property: