Why Change Styles and Classes?
style property to achieve this. For instance, let's say we have a paragraph with an id of
<p id="test">Hello, codedamn!</p>
If we want to change the color of the text to blue, we would do this:
document.getElementById("test").style.color = "blue";
getElementById is a method that fetches the element with the specified ID, and
style.color is used to change the color of the text.
Changing Multiple Styles
In a similar fashion, you can change multiple styles at once. Let's change the color and the font-size of our text:
var para = document.getElementById("test"); para.style.color = "blue"; para.style.fontSize = "20px";
Adding a Class
classList.add() function allows us to add classes to an element. Let's add a class named 'highlight' to our paragraph.
Removing a Class
As you might have guessed, we can also remove a class using the
Toggling a Class
classList.toggle() function is a little more complex. It removes a class from an element if the class exists. If it doesn't exist, it adds the class.
Q: Can I add multiple classes at once?
A: Yes, you can add multiple classes by passing them as separate arguments to the
element.classList.add("class1", "class2", "class3");
Q: Can I change the style of multiple elements at once?
A: Yes, you can select multiple elements using
querySelectorAll and then loop through them to change the style.
Q: Is there a way to check if an element has a specific class?
A: Yes, the
contains method checks if an element has a specific class.
Happy coding, and see you in the next post!
Free money-back guarantee
Unlimited access to all platform courses
100's of practice projects included
ChatGPT Based Instant AI Help (Jarvis)
Structured Full-Stack Web Developer Roadmap To Get A Job
Exclusive community for events, workshops
Sharing is caring
Did you like what Vishnupriya wrote? Thank them for their work by sharing it on social media.
No comments so far
Leave a question/feedback and someone will get back to you