<!-- TOC -->
- Introduction
- The Selectors API
- Basic jQuery to DOM API examples
- More advanced jQuery to DOM API examples
<!-- /TOC -->
jQuery and other DOM libraries got a huge popularity boost in the past, among with the other features they provided, thanks to an easy way to select elements on a page.
Traditionally browsers provided just a single way to select a DOM element - by its id
attribute, with getElementById()
, a method offered by the document
object.
Since 2013 the Selectors API, the DOM allows you to use two more useful methods:
document.querySelector()
document.querySelectorAll()
They can be safely used, as caniuse.com tells us, and they are even fully supported on IE9 in addition to all the other modern browsers, so there is no reason to avoid them, unless you need to support IE8 (which has partial support) and below.
They accept any CSS selector, so you are no longer limited by selecting elements by id
.
document.querySelector()
returns a single element, the first founddocument.querySelectorAll()
returns all the elements, wrapped in a NodeList object.
These are all valid selectors:
document.querySelector('#test')
document.querySelector('.my-class')
document.querySelector('#test .my-class')
document.querySelector('a:hover')
Here below is a translation of the popular jQuery API into native DOM API calls.
$('#test')
document.querySelector('#test')
We use querySelector
since an id
is unique in the page
$('.test')
document.querySelectorAll('.test')
$('div')
document.querySelectorAll('div')
$('div, span')
document.querySelectorAll('div, span')
$('[data-example="test"]')
document.querySelectorAll('[data-example="test"]')
$(':nth-child(4n)')
document.querySelectorAll(':nth-child(4n)')
For example all li
elements under #test
:
$('#test li')
document.querySelectorAll('#test li')