JavaScript: The Selectors API

Warning This article was written over six months ago, and may contain outdated information.

JavaScript libraries like jQuery and Pro­to­type are amaz­ing; flex­i­ble and pow­er­ful, they stan­dard­ise process­es and make cross-brows­er script­ing real­ly easy. I rarely work on a project nowa­days where a library isn’t used.

Their ease-of-use has a slight draw­back, how­ev­er: it’s easy to rely on them too much, and lose sight of new devel­op­ments in JavaScript. This was the rea­son for my not real­ly pay­ing much atten­tion to an excit­ing recent intro­duc­tion, the Selec­tors API, until I had cause to use it on a per­son­al project.

I may be com­plete­ly out of the loop, and per­haps every­one knows about this already; in case you don’t here’s a quick overview. The Selec­tors API has a pair of meth­ods which allow you to select ele­ments by using CSS selec­tors in the argu­ment string; for example:

var foo = document.querySelector('.foo p');
var bar = document.querySelectorAll('.foo p');

The first method, querySelector(), returns the first ele­ment match­ing the spec­i­fied argu­ment; the sec­ond, querySelectorAll() returns a NodeList of all ele­ments match­ing the argu­ment. So giv­en the fol­low­ing markup:

<div class="foo">
<p>It was the best of times.</p>
<p>It was the worst of times.</p>

The vari­able foo would return the first para­graph, and the vari­able bar would return a list of both para­graphs — so you could loop through the list with for, or get a sin­gle prop­er­ty value:

var barOne = bar[0];

Any­one used to work­ing with libraries like jQuery should find this pret­ty easy to grasp, as many already use a syn­tax sim­i­lar to this. Prob­a­bly the best news about this new API is that it’s already well imple­ment­ed; Fire­fox, Chrome/Safari, Opera and IE8+ all sup­port it.

One oth­er hap­py dis­cov­ery regard­ing JavaScript: the IE9 beta has sup­port for the addEventListener() method. I’m pret­ty sure I don’t need to explain that one.

Comments are closed.