How to select DOM elements by CSS selectors using JavaScript

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

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('')

// iterate over elements
divs.forEach((div, index) => { = '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(', 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.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.