JavaScript — Adding and Removing Classes From HTML Elements
In the past few articles, you’ve seen some HTML elements be referenced by their class. I want to go over how we can add and remove this via JavaScript.
Here you can see the p tag with the class of “error”. I have also linked up a stylesheet called styles.css in the Head. This is what it looks like.
I have 2 very straight-forward styles. One for an error and one for success.
So if I run this in Live Server, you’ll see that the text is red.
If I change this from an error class to success the color changes to green.
To communicate with this via JavaScript you can use the querySelector to get a reference to the p tag. I’m going to log out the classList for this p tag. You should only see 1 think in the list.
If I give this p tag more classes like so, you’ll see them logged out like this;
This is a way to get the classes. What if we want to add or remove them?
I’m going to reset the p tag to only have 1 class of “success.” I’m going to then add the error class through JavaScript.
To remove a class you can simply say something like:
para.classList.remove()
.
CHALLENGE TIME:
Here I have a list of p tags. some say “this is a bunch of error text”, some say success toext and some say no class text. Before you continue reading this… using the information we now have at our disposal, I want you to try to assign the proper class to the proper html tag. For example, I want the error text to have an error class and the success text to have a success class.
SOLUTION:
First I ned to use the querySelectorAll() to gain access to all the p tags.
I’m doing this so I can get a NodeList constaining all the p tags so I can cycle through them with a forEach loop.
Next I will use a forEach loop to cycle through all the p tags. everytime I find one whos inner text includes the word “success” I add a success class to it. The same applies for errors.
I added the if check for “no class” just in case I wanted to do something special for it later.
The RESULT!
This is my first inclination for solving this, but there are some scenarios where you may want to use the textContent property instead of the innerText property. The reason for this is because sometimes you can chose to hide certain text in your html. The innerText property only accesses the visible text in the element. The textContent property accesses all of it whether it is visible or not. So either way works, but in some cases it may be best to use textContent.
See ya in the next one!