Categories
JavaScript Selecting

JavaScript for optimizers #29: How to select multiple element types?

Example

Select multiple element types:

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

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

Breakdown

Let’s take a look at an example:

<h1></h1>
<p>Paragraph 1</p>
<div></div>
<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.

Syntax

document.querySelectorAll("elementtype, elementtype");