Alex Rivera | Logout

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

Asked 2012-11-15T11:48:58.190
9

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?

Edit
Report

2 Answers

3

Additionally: a helper to use the MatchesSelector in major browsers

function matches() {
  var el = document.querySelector('body');
  return ( el.mozMatchesSelector || el.msMatchesSelector ||
           el.oMatchesSelector   || el.webkitMatchesSelector || 
           {name:'getAttribute'} ).name;
}
//=> usage
var someP = document.querySelector('p');
   ,rightClass = someP[matches()]('.someclass');

Still, /someclass/.test(someP.className) would be shorter here ;)

answered 2012-11-15T12:48:15.420
1

Generally, given element e, to check if it matches a selector you would use:

var check = false;
var c = e.parentNode.querySelectorAll('selector');
for(var i = 0; i < c.length; i++){
    if (c[i]==e){
        check = true;
    }
}

A more concise, but somewhat hacky solution is:

var c = e.parentNode.querySelectorAll('selector');
var check = Array.prototype.indexOf.call(c,e) != -1;

NOTE: check indicates whether or not the element matches the selector.

Here's a demo: http://jsfiddle.net/2vX3z/

answered 2012-11-15T11:54:29.037

Your Answer