How to select multiple element types?

Table of Contents


Select multiple element types:

let h1AndParagraphs = document.querySelectorAll("h1, p");

Try it out for yourself by going to the testing page and running the code in the browser console.

Tip: Press Command+Option+J (Mac) or Control+Shift+J (Windows, Linux, Chrome OS) to open the chrome console.

We select the h1 and all paragraphs


Let’s take a look at an example:

<p>Paragraph 1</p>
<p>Paragraph 2</p>

This example has an h1 element with two paragraphs and a div. We want to select all paragraphs and divs.

let divsAndParagraphs = document.querySelectorAll("div, p");

This line of code will do that. Between the parentheses, we can separate multiple selectors with a comma. This way the method knows we want to select different element types.

Instead of the standard querySelector method, we use the querySelectorAll method. This way we can select multiple elements and store them in an array.

We assign the array to the newly declared divsAndParagraphs variable.


document.querySelectorAll("elementtype, elementtype");