tags:

views:

142

answers:

3

Let's say I've got a DOM element - how can I tell if 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, does 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 if a DOM element matches a jquery selector...

+4  A: 

You can use the is() method:

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

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")

Jeff Davis
A: 

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.

Peter Boughton