Categories
JavaScript Selecting

JavaScript for optimizers #23: How to select an element with a class?

Example

Select an element with a class:

let testImage = document.querySelector(".wp-image-1596");
console.log(testImage);

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

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

The image with the class wp-image-1596 is selected
The image with the class wp-image-1596 is selected

Breakdown

Selecting an element with a class can be done with a few simple lines of code.

Let’s take a look at some example HTML code.

<img class="background">

This is an image element of a webpage. This element has the attribute called class with the value background assigned to it. This means we can identify this element using its class.

We can select elements with classes using the document.querySelector method.

document.querySelector(".background");

By inputting a class name preceded with a period between the parentheses we tell this method we are looking for the first element on the webpage that has this class.

Let’s take a look at an example of selecting an element and assigning it to a variable.

let backgroundImage = document.querySelector(".background");

First, we declare a variable called backgroundImage with the let keyword. Then we assign the first element on the webpage with the class background to the variable.

When we console.log this variable we get the element we selected as the output.

console.log(backgroundImage);

Syntax

let variableName = document.querySelector(".class");