DOM Retrieving Elements Query Selectors


Example

In modern browsers [1], it is possible to use CSS-like selector to query for elements in a document -- the same way as sizzle.js (used by jQuery).

querySelector

Returns the first Element in the document that matches the query. If there is no match, returns null.

// gets the element whose id="some-id"
var el1 = document.querySelector('#some-id');
 
// gets the first element in the document containing "class-name" in attribute class
var el2 = document.querySelector('.class-name');
 
// gets the first anchor element in the document
var el2 = document.querySelector('a');
 
// gets the first anchor element inside a section element in the document
var el2 = document.querySelector('section a');

querySelectorAll

Returns a NodeList containing all the elements in the document that match the query. If none match, returns an empty NodeList.

// gets all elements in the document containing "class-name" in attribute class
var el2 = document.querySelectorAll('.class-name');
 
// gets all anchor elements in the document
var el2 = document.querySelectorAll('a');

// gets all anchor elements inside any section element in the document
var el2 = document.querySelectorAll('section a');