Accessing DOM elements using querySelector and querySelectorAll
The Selectors API is a useful feature provided by the DOM that allows you to easily select elements on a page. It offers two methods: document.querySelector() and document.querySelectorAll().
Introducing the Selectors API
Traditionally, browsers only provided a single way to select a DOM element - by its id attribute using the getElementById() method offered by the document object. However, with the introduction of the Selectors API in 2013, you now have more options.
The Advantages of querySelector and querySelectorAll
Unlike getElementById(), querySelector and querySelectorAll accept any CSS selector, so you are no longer limited to selecting elements by id. This gives you more flexibility in selecting the elements you need.
Here’s what you need to know about these two methods:
- document.querySelector(): This method returns a single element, specifically the first one found, based on the CSS selector provided.
- document.querySelectorAll(): This method returns all the elements that match the CSS selector, wrapped in a NodeList object.
Example Usage: Basic jQuery to DOM API
Let’s take a look at some basic examples that demonstrate how to use querySelector and querySelectorAll as an alternative to the jQuery API.
- Select by id:
// jQuery
$('#test')
// DOM API
document.querySelector('#test')
Here, we use querySelector instead of the jQuery selector since an id is unique on a page.
- Select by class:
// jQuery
$('.test')
// DOM API
document.querySelectorAll('.test')
- Select by tag name:
// jQuery
$('div')
// DOM API
document.querySelectorAll('div')
Example Usage: More Advanced jQuery to DOM API
Now, let’s explore some more advanced examples that demonstrate how querySelector and querySelectorAll can be used for more specific selections.
- Select multiple items:
// jQuery
$('div, span')
// DOM API
document.querySelectorAll('div, span')
- Select by HTML attribute value:
// jQuery
$('[data-example="test"]')
// DOM API
document.querySelectorAll('[data-example="test"]')
- Select by CSS pseudo class:
// jQuery
$(':nth-child(4n)')
// DOM API
document.querySelectorAll(':nth-child(4n)')
- Select descendants of an element:
For example, if we want to select all li elements under #test:
// jQuery
$('#test li')
// DOM API
document.querySelectorAll('#test li')
Conclusion
By using querySelector and querySelectorAll, you can easily access DOM elements using any CSS selectors. These methods are widely supported in modern browsers, making them a great alternative to jQuery for selecting and manipulating elements.