The matchesSelector Method
About
The matchesSelector
method is defined on HTMLElement
objects. It accepts as argument a string of CSS selectors and returns a boolean representing whether the element is matched by the selector.
For example, if a document contained the following markup:
<div id="theDiv" class="theClass"><h1 id="theHeader">The Header</h1></div>
Then, if the div
were placed in a variable, we could use the method to test whether it matches an arbitrary selector.
var theDiv = document.getElementById("theDiv"); theDiv.matchesSelector("div"); /* true */ theDiv.matchesSelector("#theDiv"); /* true */ theDiv.matchesSelector(".theClass"); /* true theDiv.matchesSelector("div#theDiv.theClass"); /* true */ theDiv.matchesSelector("h3"); /* false */ var theHeader = document.getElementById("theHeader"); theHeader.matchesSelector("div>h1"); /* true */
An Important Note on Vendor Prefixing
The matchesSelector
method as it appears above is written according to the specification in the W3C Selectors API1. However, at the time of this writing no browser implements the method according to this spec.
Instead, it must be prefixed with a vendor prefix. Specifically, in Gecko-based browsers such as FireFox, the method must be written as mozMatchesSelector
. In Webkit-based browsers it must be written as webkitMatchesSelector
.
The reason for this inconsistency is because the method was implemented in these engines before a specification existed, and we are therefore forced to call a completely different function depending on the rendering engine.
<div id="theDiv" class="theClass"><h1 id="theHeader">The Header</h1></div>
In this case, Tizen uses Webkit to render web apps, so we will always call the webkitMatchesSelector
version of this method in the demo code.
Demo
The markup below represents the code you're selecting against.
<div id="theDiv" class="theClass"> <h1 id="theHeader">The Header</h1> <p id="theParagraph" class="theClass"> <span id="theSpan">Some words</span> </p> </div>
Type a selector into the textbox below and see which elements match it.
DIV | |
---|---|
H1 | |
P | |
SPAN |
The source code for this demo is below.
var selector = document.getElementById("selector"), div = document.getElementById("theDiv"), h1 = document.getElementById("theHeader"), p = document.getElementById("theParagraph"), span = document.getElementById("theSpan"), divRes = document.getElementById("divResult"), h1Res = document.getElementById("h1Result"), pRes = document.getElementById("pResult"), spanRes = document.getElementById("spanResult"); selector.onkeyup = function() { setTimeout( function() { var sel = selector.value; divRes.innerText = div.webkitMatchesSelector(sel); h1Res.innerText = h1.webkitMatchesSelector(sel); pRes.innerText = p.webkitMatchesSelector(sel); spanRes.innerText = span.webkitMatchesSelector(sel); }, 20 ); };
References
- http://www.w3.org/TR/selectors-api2/
- https://developer.mozilla.org/en/DOM/
Element.mozMatchesSelector