JavaScript provides two methods, querySelector() and querySelectorAll(), to select DOM elements based on CSS selectors. CSS selectors are a simple yet powerful way of selecting HTML elements from the document.

The querySelector() method takes a CSS selector as input and returns the first element that matches the given selector. If no HTML element is found, it returns null.

Here is an example that selects the first <button> element in the document:

const p = document.querySelector('p')

// Get paragraph text
console.log(p.innerText)

The querySelectorAll() method takes a CSS selector as input and returns a list of DOM elements, basically a NodeList, that match the given CSS selector. If no match is found, it returns an empty list.

Here is an example that selects all <div> elements that contains the active CSS class:

const divs = document.querySelectorAll('div.active')

// iterate over elements
divs.forEach((div, index) => {
  div.style.color = 'red'
})

In the example above, we used the forEach() loop to iterate through the elements of NodeList. Read this guide to learn more about looping over DOM elements in JavaScript.

You can also specify multiple CSS selectors separated by comma with querySelectorAll(), just like the jQuery's $(...) method:

// select all <div> tags with the `active` class + all <p> tags
const elems = document.querySelectorAll('div.active, p')

Both these methods work in all modern and old browsers up to Internet Explorer 8. Take a look at the how to select DOM elements guide to learn more about different ways of extracting DOM elements in JavaScript.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.