最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check element against querySelector? (using native methods, not JQuery) - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Nov 15, 2012 at 11:59 mikemaccana asked Nov 15, 2012 at 11:48 mikemaccanamikemaccana 123k110 gold badges427 silver badges531 bronze badges 8
  • querySelector operates on descendants, not children. – user1726343 Commented Nov 15, 2012 at 11:50
  • @Asad: Children and descendants are generally used interchangeably, much in the same way that parent and antecedents are. If you really like I can change the terminology. – mikemaccana Commented Nov 15, 2012 at 11:51
  • I'm not sure why this would be useful: why can't you just query the className or Attributes of the given Element? – KooiInc Commented Nov 15, 2012 at 11:58
  • @KooiInc I could indeed write something that checks className, ID, Attributes etc. But the resultant code would seem like a copy of something that already exists in the form of querySelector. – mikemaccana Commented Nov 15, 2012 at 12:00
  • Well, the alternative looks more expensive: one way or another you'll have to loop a collection of Nodes and compare them to the given node to be sure you're operating on the right node. Having the node already available, querying its attributes/properties seems more obvious. One can drive a nail into wood using a screw driver, but a hammer is more suitable. – KooiInc Commented Nov 15, 2012 at 12:08
 |  Show 3 more comments

4 Answers 4

Reset to default 13

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)

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

Not in all browsers, but this might be helpful: http://caniuse.com/matchesselector

Example usage (from MDN page);

<div id="foo">This is the element!</div>
  <script type="text/javascript">
    var el = document.getElementById("foo");
    if (el.mozMatchesSelector("div")) {//or webkitMatchesSelector("div") in webkit browser or msMatchesSelector("div") in IE9/10
      alert("Match!");
    }
  </script>

Supose the only other way is to run querySelector and loop through all items testing if it is the same as one you already have.

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/

发布评论

评论列表(0)

  1. 暂无评论