Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
371 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use the is() method:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...