# How to select DOM elements by CSS selectors using JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Mar 6, 2020, updated Oct 15, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-select-dom-elements-by-css-selectors

> A simple guide to learn how to select DOM elements using CSS selectors in JavaScript.

JavaScript provides two methods, `querySelector()` and `querySelectorAll()`, to select [DOM](https://attacomsian.com/blog/getting-dom-elements-javascript) 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:

```javascript
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](https://attacomsian.com/blog/javascript-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](https://attacomsian.com/blog/javascript-check-if-element-contains-css-class) the `active` CSS class:

```javascript
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()](https://attacomsian.com/blog/javascript-foreach) loop to iterate through the elements of `NodeList`. Read [this guide](https://attacomsian.com/blog/javascript-loop-dom-elements) 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:

```javascript
// 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](https://attacomsian.com/blog/getting-dom-elements-javascript) guide to learn more about different ways of extracting DOM elements in JavaScript.
