Categories
JavaScript Selecting

JavaScript for optimizers #27: How to select an element type that has a class?

Example

Select an element type that has a class:

let leadParagraph = document.querySelector("p.leadParagraph");
console.log(leadParagraph);

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.

The first paragraph with the appropriate class gets selected

Breakdown

With this method, you can select element types with specific classes.

Let’s take a look at an example:

<p></p>
<p class="leadParagraph"></p>
<p></p>

In this example, we have three paragraph elements. We only want to select the second paragraph with a class.

let leadParagraph = document.querySelector("p.leadParagraph");

We use the querySelector method to select an element of the DOM. Between the parentheses, we input a string that contains our selector.

The first thing we define is the element type paragraph with the letter p. Then we add a period to tell the method we want to select a class. After that, we add the class name. In our example, this is the leadParagraph class.

We assign the selected element to the newly declared leadParagraph variable.

You can console.log the variable to make sure you have the right one.

console.log(leadParagraph);

Syntax

document.querySelector("elementtype.class");