找出querySelector的哪個部分與給定元素匹配

[英]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?

有沒有可能找出querySelector的哪個部分與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?

如果你使用document.querySelectorAll,我如何回溯我負責在DOM中查找元素的查詢片段?

1 个解决方案

#1


2  

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

您可以使用Element.matches,它目前有合理的支持。

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

如果元素將由指定的選擇器字符串選擇,則Element.matches()方法返回true;否則,返回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

我們正在使用Array.forEach但更重要的是使用Array.filter傳遞Element.matches方法,因此它會過濾掉選擇器,返回一個Array,我們通過Array.join連接它來輸出到控制台


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/02/21/7299e707f734c4eaa8d6b0b134156b5b.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com