How to check if an element matches a selector?
Hello,
is there any way one can test if an element matches a jQuery selector?
I'm not trying to locate elements, just test for match.
More specifically, when using event delegation and a common callback
function for multiple events, is there a way to check the event's
currentTarget against a selector?
In the following example, how can I check if the currentTarget is
the LI node with class "item2"?
- <!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<ul id="#foo">
<li class="item1">Item1</li>
<li class="item2">Item2</li>
</ul>
<p id="#bar">Paragraph</p>
<script>
$(function() {
$("body").delegate("li, p", "click", function(e) {
if (e.currentTarget.nodeName == "P") { //works
//do something for p
}
else if (e.currentTarget.nodeName == "LI" &&
$(e.currentTarget).attr("class") == "item2") { //works, but ugly
//do something for item2
}
});
});
</script>
</body>
</html>
This works but will also match the LI item with class "item1":
if ($(e.currentTarget).parent().find(">LI.item2").length
I would like to use a selector to check to element against, something like:
if ($(e.currentTarget).test(">LI.item2").length
that checks if the elements match the selector.
Cheers,
Tomas