Skip to content
Advertisement

Check element against querySelector? (using native methods, not JQuery)

I have an Element. I would like to check whether it meets a particular query, eg (‘.someclass’) in the same kind of style as querySelector.

This isn’t as easy as it sounds. Element.querySelectorAll and Element.querySelector only work on descendents of the element in question. Not the element itself.

var p = document.querySelector('p')

Note: The line above is for illustration purposes only. In real life, I’ve actually found the element by some other means.

p.querySelector('p')

Returns null. Because querySelector only operates on descendents.

I could do:

p.parentNode.querySelector('.someclass')

But that would return the first child of the element’s parent, which may be a different element. This code would fail, for example, if ‘p’ was the second child of the parent.

How can I check if an element itself meets a query?

Advertisement

Answer

You can use the matches() method.

Support can be found at http://caniuse.com/matchesselector


But since it is still a draft, all browsers implement it with a prefix (it was a draft in 2012)

  • element.msMatchesSelector( selector ) (IE)
  • element.mozMatchesSelector( selector ) (mozilla)
  • element.webkitMatchesSelector( selector ) (webkit)
  • element.oMatchesSelector( selector ) (Opera)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement