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.
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.
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.
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.
let variableName = document.querySelector(".class");