JavaScript: The Selectors API

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

JavaScript libraries like jQuery and Prototype are amazing; flexible and powerful, they standardise processes and make cross-browser scripting really easy. I rarely work on a project nowadays where a library isn’t used.

Their ease-of-use has a slight drawback, however: it’s easy to rely on them too much, and lose sight of new developments in JavaScript. This was the reason for my not really paying much attention to an exciting recent introduction, the Selectors API, until I had cause to use it on a personal project.

I may be completely out of the loop, and perhaps everyone knows about this already; in case you don’t here’s a quick overview. The Selectors API has a pair of methods which allow you to select elements by using CSS selectors in the argument string; for example:

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

The first method, querySelector(), returns the first element matching the specified argument; the second, querySelectorAll() returns a NodeList of all elements matching the argument. So given the following markup:

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

The variable foo would return the first paragraph, and the variable bar would return a list of both paragraphs — so you could loop through the list with for, or get a single property value:

var barOne = bar[0];

Anyone used to working with libraries like jQuery should find this pretty easy to grasp, as many already use a syntax similar to this. Probably the best news about this new API is that it’s already well implemented; Firefox, Chrome/Safari, Opera and IE8+ all support it.

One other happy discovery regarding JavaScript: the IE9 beta has support for the addEventListener() method. I’m pretty sure I don’t need to explain that one.

Comments are closed.