Meet the Selectors API
DOM Scripting is sometimes clunky. Consider the retrieval of elements with a particular class name. The code might look like this:
var p = document.getElementsByTagName('p');
var newsitems = [];
var i;
for(i = 0; i < p.length; i++){
if( p[i].className == 'newsitem' ){
newsitems.push( p[i] );
}
}
In the example above, we’ve retrieved all elements in the document using
document.getElementsByTagName()
. Then we’ve iterated over them,
checking for the presence of the desired class name.
It’s ugly, right? That᾿s even more true when you look at the elegant, CSS-style selectors of libraries like jQuery and MooTools.
Code like that above is why the W3C developed a Selectors
API. It consists of two methods on
the document object: querySelector()
and querySelectorAll()
.
querySelector()
and querySelectorAll()
both accept any CSS selector
that the browser supports. All recent browser
releases support both
methods, though Internet Explorer 8 is limited to CSS2 selectors.
querySelectorAll()
, as its name suggests, returns a node list of
elements matching the given selector. querySelector()
only returns the
first matching element. You can pass any CSS selector as an argument,
including ones like the adjacent sibling combinator and nth-child()
if
the browser supports it.
Let's re-write the above code using querySelectorAll()
.
var newsitems = document.querySelectorAll('.newsitem');
That's much more concise. The newsitems
variable contains only those
elements with the newsitem
class. Using the Selectors API greatly
simplifies the code we need to use when interacting with the DOM.