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;
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.
addEventListener() method. I’m pretty sure I don’t need to explain that one.