/

The Selectors API: querySelector and querySelectorAll

The Selectors API: querySelector and querySelectorAll

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:

  1. document.querySelector(): This method returns a single element, specifically the first one found, based on the CSS selector provided.
  2. 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.

  1. Select by id:
1
2
3
4
5
// jQuery
$('#test')

// DOM API
document.querySelector('#test')

Here, we use querySelector instead of the jQuery selector since an id is unique on a page.

  1. Select by class:
1
2
3
4
5
// jQuery
$('.test')

// DOM API
document.querySelectorAll('.test')
  1. Select by tag name:
1
2
3
4
5
// 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.

  1. Select multiple items:
1
2
3
4
5
// jQuery
$('div, span')

// DOM API
document.querySelectorAll('div, span')
  1. Select by HTML attribute value:
1
2
3
4
5
// jQuery
$('[data-example="test"]')

// DOM API
document.querySelectorAll('[data-example="test"]')
  1. Select by CSS pseudo class:
1
2
3
4
5
// jQuery
$(':nth-child(4n)')

// DOM API
document.querySelectorAll(':nth-child(4n)')
  1. Select descendants of an element:

For example, if we want to select all li elements under #test:

1
2
3
4
5
// 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.

tags: [“selectors api”, “querySelector”, “querySelectorAll”, “DOM elements”, “CSS selector”]