<div class="a">
<span class="a">a</span>
<span class="a">b</span>
<span class="a">c</span>
</div>
Assuming I have a variable called divA
representing the top level div node. divA.querySelectorAll('.a')
will return a list of the 3 span.a
s. I wonder if there's an easy way to return a list of 4 elements including the divA itself?
I know I could start from a higher level node, but let's assume there might be other .a
elements that I don't want to mess with them.
In reality I still need to test whether divA
matches my selector or not. So is there a way for css selector to test an element itself?
I could create a parent node and run querySelectorAll from there. But if there's an easier way, I don't need to go that far.
<div class="a">
<span class="a">a</span>
<span class="a">b</span>
<span class="a">c</span>
</div>
Assuming I have a variable called divA
representing the top level div node. divA.querySelectorAll('.a')
will return a list of the 3 span.a
s. I wonder if there's an easy way to return a list of 4 elements including the divA itself?
I know I could start from a higher level node, but let's assume there might be other .a
elements that I don't want to mess with them.
In reality I still need to test whether divA
matches my selector or not. So is there a way for css selector to test an element itself?
I could create a parent node and run querySelectorAll from there. But if there's an easier way, I don't need to go that far.
Share Improve this question edited Jan 21, 2020 at 10:25 asked Jan 21, 2020 at 10:18 user1663023user1663023 3 |2 Answers
Reset to default 12I still need to test whether divA matches my selector or not. Is there a way for css selector to test an element itself?
querySelector()
cannot return the context element it's running on.
What you can do is use @Andreas' solution followed by a filter()
/matches()
combo.
[divA, ...divA.querySelectorAll('.a')].filter(el => el.matches('.a'));
This is what you're looking for I guess: :scope
EDIT: Just like in this answer: https://stackoverflow.com/a/43354126/14034888
const parent = document.querySelector('.parent');
console.log(parent.querySelectorAll(':scope .box'));
should return (if it exists in the DOM of course) a NodeList of length 5 with .parent
as the first element in the list and the children (and grand children) filling the remaining four indices...
<div class='parent box'>
<div class='box'></div>
<div class='box'>
<div class='inner box'></div>
</div>
<div class='box'></div>
</div>
[divA, ...divA.querySelectorAll('.a')]
– Andreas Commented Jan 21, 2020 at 10:19[divA, ...divA.querySelectorAll('.a')]
– Roberto Zvjerković Commented Jan 21, 2020 at 10:20