DOM: Selectors API and querySelectorAll

A new and powerful feature of the DOM is the Selectors API specification, which allows developers to use a CSS syntax to select elements in the DOM tree. The new method that works behind the scenes is querySelectorAll() which converts CSS selectors to retrieve the elements and values that we want from the DOM tree. Its syntax is as follows:

var selector = document.querySelectorAll('#test #foo');

In this case, given the above CSS selectors this method will return a direct reference to a node with ID equal to foo. As you can see, in this case it's just as when we write:

var selector = document.getElementById('test').getElementById('foo');

But this method can also return a NodeList, depending on the CSS selectors we use as query. For example, given the following DOM snippet:

<ul id="test">

We want to select the text of the span element. Using querySelectorAll() we can write:

function query(querySelector) {
     querySelector = querySelector || 'body';
  var selector = document.querySelectorAll(querySelector);
window.onload = function() {
  query('#test li:nth-child(2) > span'); // alerts 'Test'

We're using an array-like syntax to access our node because in this case we're working with a NodeList object. In a nutshell: to properly use this new method, always make sure that the returned value be in the format that you do expect.

Leave a Reply

Note: Only a member of this blog may post a comment.