Adrian
Adrian

Reputation: 23

Find out which part of a querySelector matched a given element

Is there any possibility to find out which part of a querySelector matched a specific element in the DOM?

Let's say you have the following query:

'h1,h2,h3,h4.custom-bg,div'

If you use document.querySelectorAll, how can I backtrace the fragment of my query that was responsible for finding the element in the DOM?

Upvotes: 1

Views: 184

Answers (1)

Amit Joki
Amit Joki

Reputation: 59252

You can use Element.matches, which has a reasonable support as of now.

The Element.matches() method returns true if the element would be selected by the specified selector string; otherwise, returns false.

You would use something like this

var str = 'h1,h2,h3,h4.custom-bg,div';
[].forEach.call(document.querySelectorAll(str), function(elm){
   var slctrMatched = str.split(",").filter(elm.matches);
   console.log(slctrMatched.join(" "));
});

We are making use of Array.forEach but more importantly, Array.filter, which is passed Element.matches method, so it filters out the selectors, returning an Array, which we are outputting to console by joining it by Array.join

Upvotes: 4

Related Questions