Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
-2
rated 0 times [  4] [ 6]  / answers: 1 / hits: 5086  / 4 Years ago, tue, january 21, 2020, 12:00:00
<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.as. 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.


More From » javascript

 Answers
1

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'));

[#4993] Friday, January 17, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jonrened

Total Points: 627
Total Questions: 114
Total Answers: 99

Location: Zimbabwe
Member since Thu, Jul 21, 2022
2 Years ago
jonrened questions
Mon, Nov 2, 20, 00:00, 4 Years ago
Tue, May 19, 20, 00:00, 4 Years ago
Thu, Nov 7, 19, 00:00, 5 Years ago
Mon, Aug 26, 19, 00:00, 5 Years ago
;