是否有可能找出 querySelector 的哪一部分与 DOM 中的特定元素匹配?
假设您有以下查询:
'h1,h2,h3,h4.custom-bg,div'
如果您使用 document.querySelectorAll,我如何回溯负责在 DOM 中查找元素的查询片段?
最佳答案
您可以使用Element.matches
,其中有 reasonable support截至目前。
The
Element.matches()
method returns true if the element would be selected by the specified selector string; otherwise, returns false.
你会使用这样的东西
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(" "));
});
我们正在使用Array.forEach
,但更重要的是,Array.filter
,它是通过Element.matches
方法传递的,所以它过滤掉选择器,返回一个数组,我们通过 Array.join
关于javascript - 找出 querySelector 的哪一部分与给定元素匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28648007/