Remove Css Class from Element with Javascript (No Jquery)

When working with JavaScript, there may be times when you need to remove a CSS class from an element. While jQuery offers a convenient method for achieving this, it is also possible to accomplish the same task using pure JavaScript.

Method 1: Using the classList property

The classList property provides an easy way to manipulate CSS classes on an element. To remove a class from an element, you can use the classList.remove() method.

Here’s an example:

const element = document.getElementById('myElement');
element.classList.remove('myClass');

In this example, we first select the element using its ID. Then, we call the classList.remove() method and pass in the name of the class we want to remove.

Method 2: Using the className property

If you prefer a more traditional approach, you can also remove a CSS class by manipulating the className property of an element.

Here’s an example:

const element = document.getElementById('myElement');
element.className = element.className.replace('myClass', '');

In this example, we select the element using its ID and then use the replace() method to remove the desired class from the className string.

Conclusion

Both methods described above allow you to remove a CSS class from an element using pure JavaScript. Whether you prefer the simplicity of the classList property or the familiarity of the className property, you can achieve the desired result without relying on jQuery.

Remember to always test your code in different browsers to ensure cross-browser compatibility.

That’s it for this post! Happy coding!


Posted

in

, , ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *