querySelectorAll to include self
<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.
I 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'));