JavaScript provides two methods, querySelector() and querySelectorAll(), to select DOM elements based on CSS selectors. CSS selectors are very 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 the matches the given selector. If no element is matched, 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. Take a look at 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 how to select DOM elements guide to learn more about different ways of extracting DOM elements in JavaScript.

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Subscribe to RSS Feed.

👋 If you enjoy reading my articles and want to support me to continue creating free tutorials, ☕ Buy me a coffee (cost $5).