[英]How can I tell whether an element matches a selector?
Let's say I've got a DOM element - how can I tell whether it matches a jQuery selector, such as p
or .myclass
?假设我有一个 DOM 元素 - 我如何判断它是否匹配 jQuery 选择器,例如
p
或.myclass
? It's easy to use the selector to match children of the element, but I want a true/false answer to whether this particular element match?使用选择器来匹配元素的子元素很容易,但我想要这个特定元素是否匹配的真/假答案?
The element may not have an ID (and I can't assign it a random one for reasons beyond this), so I can't apply my selector to the element's parent and look for children with the same ID as mine.该元素可能没有 ID(出于其他原因,我无法为其分配一个随机 ID),因此我无法将选择器应用于元素的父级并查找与我的 ID 相同的子级。
Will this work as intended?这会按预期工作吗? I can't figure out Javascript object comparisons.
我无法弄清楚 Javascript 对象比较。
$(selector, myElement.parentNode).each({
if (this == myElement) // Found it
});
Seems like there would be an easy way to see whether a DOM element matches a jQuery selector...似乎有一种简单的方法可以查看 DOM 元素是否与 jQuery 选择器匹配......
var elements = document.querySelectorAll('div'); console.log( elements[0].matches('.foo'), // true elements[0].matches('.bar'), // false elements[1].matches('[title=bar]'), // true )
<div class='foo'></div> <div title='bar'></div>
I can't apply my selector to the element's parent and look for children with the same ID as mine.
我无法将我的选择器应用于元素的父元素并寻找与我的 ID 相同的子元素。
You can't do that anyway - the id
attribute must be unique.无论如何您都不能这样做 -
id
属性必须是唯一的。
Maybe you just want:也许你只是想要:
$(".complicated #selector p.with > div.manyParts").length
If there are no matches, length returns 0, which is falsy, so you can use it in an if
statement, like:如果没有匹配,长度返回 0,这是假的,所以你可以在
if
语句中使用它,比如:
if($(".doesThis #exist").length) {
// Do things
}
Probably would be worth storing it in a separate variable and THEN checking the length;可能值得将它存储在一个单独的变量中,然后检查长度; that way, if you need to do anything with the matched elements, you don't have to execute the same selector again.
这样,如果您需要对匹配的元素做任何事情,您不必再次执行相同的选择器。
Try Element.matches()
试试
Element.matches()
document.addEventListener("click", event => {
if (event.target.matches(".elementsClass")) {
// It matches
} else {
// Does not match
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.