JavaScript

How to change an element class with JavaScript

April 9, 2022

How to change an element class with JavaScript

In this article we will learn how to change the class of an element with JavaScript – to be able to manipulate the CSS styles that define the tag.

change an element class with JavaScript thumb

What’s up programmers, how are you all? Let’s learn more about JavaScript and DOM manipulation!

The main idea here is to first select the element

Then we must delete the class that we no longer need the element and finally add the class we want

Or maybe we’re just going to add a class, you can use this code that we’re going to see here to solve this problem too

Let’s see this running in practice:

let el = document.getElementById('element');

el.classList.remove('test');

el.classList.add('testing');

In the first line we select the element with id testing

Then using the classList property, which is the collection of the element classes, followed by the remove method, which will remove the class set by parameter

Finally we use add, which will add the class set by parameter

That is, with remove we can remove classes from an element, and add we can add classes to it

Conclusion

In this article we learned how to change the class of an element with JavaScript

And this is done in a simple way when we have already selected the element, we can access its classList property, which will give us all the classes of the same

We also have add and remove methods, which add and remove classes respectively

Do you wanna 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