Remove a specific CSS class from an HTML element with JavaScript/jQuery
This post will discuss how to remove a specific CSS class from an HTML element using JavaScript and jQuery.
1. Using jQuery
With jQuery, you can use the .removeClass() method for removing the specific class from an element. This is demonstrated below, where removeClass() is used to remove the color class from the div container.
JS
|
1 2 3 |
$(document).ready(function() { $("#container").removeClass("color"); }); |
CSS
|
1 2 3 4 5 6 7 8 9 |
.main { width: 500px; height: 300px; border: 1px solid black; } .color { background-color: lightgray; } |
HTML
|
1 |
<div id="container" class="main color"></div> |
However, this won’t remove any inline styles applied to the element using the style attribute. You can also specify the list of CSS classes to be removed from the element, as shown below. Spaces should separate the multiple classes.
JS
|
1 2 3 |
$(document).ready(function() { $("#container").removeClass("border margin"); }); |
CSS
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
.size { width: 500px; height: 300px; } .border { border: 1px solid black; } .margin { margin: 10px; } .color { background-color: lightgray; } |
HTML
|
1 |
<div id="container" class="size border color margin"></div> |
2. Using JavaScript
In plain JavaScript, you can use the Element.classList.remove() method to remove the specific class from an element. Like jQuery’s removeClass() method, this won’t remove any inline styles applied to the element using the style attribute.
JS
|
1 |
document.getElementById("container").classList.remove("color"); |
CSS
|
1 2 3 4 5 6 7 8 9 |
.main { width: 500px; height: 300px; border: 1px solid black; } .color { background-color: lightgray; } |
HTML
|
1 |
<div id="container" class="main color"></div> |
That’s all about removing a specific CSS class from an HTML element using JavaScript and Query.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)