我如何知道一个元素是否匹配一个选择器? [英] How can I tell whether an element matches a selector?
问题描述
p
或 .myclass
?很容易使用选择器来匹配元素的子元素,但是我想要一个真/假的答案是否这个特定的元素匹配? 元素可能没有ID (因为超出这个原因我不能指定一个随机的),所以我不能将我的选择器应用到元素的父母,并且寻找与我的ID相同的孩子。
这项工作是否符合预期?我无法弄清楚Javascript对象的比较。
$(selector,myElement.parentNode).each({
if(this == myElement)// Found它
});
似乎会有一个简单的方法来查看一个DOM元素是否匹配一个jQuery选择器...
您可以使用 is()
方法:
if $(this).is(p)){
// ...
}
Let's say I've got a DOM element - how can I tell whether it matches a jQuery selector, such as p
or .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.
Will this work as intended? I can't figure out Javascript object comparisons.
$(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...
You can use the is()
method:
if($(this).is("p")){
// ...
}
这篇关于我如何知道一个元素是否匹配一个选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!