sam
sam

Reputation:

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? 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...

Upvotes: 19

Views: 6242

Answers (6)

vsync
vsync

Reputation: 130810

Without jQuery, using Element.matches():

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>


See supported browsers list

Upvotes: 7

CloudBranch
CloudBranch

Reputation: 1604

Try Element.matches()

Element.matches()

document.addEventListener("click", event => {
  if (event.target.matches(".elementsClass")) {
    // It matches
  } else {
    // Does not match
  }
});

Upvotes: 0

tandrewnichols
tandrewnichols

Reputation: 3456

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:

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.

Upvotes: 1

Peter Boughton
Peter Boughton

Reputation: 112240

I can't apply my selector to the element's parent and look for children with the same ID as mine.

You can't do that anyway - the id attribute must be unique.

Upvotes: 1

Jeff Davis
Jeff Davis

Reputation: 4807

I believe the is() method is what you are looking for.

Otherwise, you might just try selecting the item directly, if that is what you mean.

So if it's an "a" with a class of "myclass", just do $("a.myclass")

Upvotes: 2

Zach
Zach

Reputation: 24786

You can use the is() method:

if($(this).is("p")){
 // ...
}

Upvotes: 37

Related Questions