JavaScript

Select element by class with JavaScript (querySelector)

December 4, 2021

Select element by class with JavaScript (querySelector)

In this article, we will learn how to select element by class in the JavaScript language, so that the necessary changes are then made via the DOM.

select element by class cover

What’s up, programmer, let’s learn something new?

Watch this content on YouTube:

In JavaScript we have several ways to select elements and make changes to their aspects via DOM

We can select by id, tags and also classes, which is what we’ll cover in this post

The method for selecting an element by class is getElementsByClassName

It must be called by the document and as we are using one class per selector, it has an important peculiarity

If there are two elements with the same class, the method will bring them both. Isn’t that cool?

So look at the syntax:

// Select by class name
let els = document.getElementsByClassName("elementClass");

This way it is possible to select elements via class with JavaScript

Note: do not add the ( . ) of the class as it is done in CSS, just its name

If you choose to select only one element, the best options would be by id or query selector, see the syntax:

// Select by id
let el = document.getElementById("id");

// Select element by CSS selector
let el2 = document.querySelector(".someClass");

These two samples will only bring a single element

Remembering that the querySelector expects a CSS selector, that is, using # for ids and ( . ) for classes

As for getElementById, just the id name in text

Conclusion

We learned that to select one element per class and multiple elements we also use the getElementsByClassName method

If our option is for only one element, it is better to prefer the methods: getElementById or querySelector

Want to learn more about JavaScript? Click here!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x