JavaScript Selecting

JavaScript for optimizers #25: How to select an element with multiple classes?


Select an element with multiple classes:

let testImage = document.querySelector(".classOne.classTwo");

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 image that contains the two classes gets selected
The image that contains the two classes gets selected


This method can be used to select images that contain two specific classes.

<img class="classOne">
<img class="classTwo">
<img class="classOne classTwo"><!-- This image gets selected -->

In this example, we see three images with different classes. The image element that contains both classOne and classTwo gets selected.

let testImage = document.querySelector(".classOne.classTwo");

We select the element using the querySelector method. By combining two classes between the parentheses we can make such a specific selection. Make sure to contain the classes in a string by placing them between quotation marks.

The element gets saved to the newly declared testImage variable.

You can console.log this variable to verify that you have selected the right element.