EN
JavaScript - how to remove class from div
1
answers
6
points
How can I dynamically remove class from element using JavaScript?
For example, I have this code and would like to remove my-class-2
.
After removal of this class, the element should not have this class and background.
My code:
// ONLINE-RUNNER:browser;
<!doctype html>
<html lang="en">
<style>
.my-class-1 {
border: 3px solid red;
padding: 5px;
width: 200px;
}
.my-class-2 {
background: yellow;
}
</style>
<body>
<div class="my-class-1 my-class-2" id="my-element">
Some text
</div>
</body>
</html>
1 answer
5
points
Quick solution:
function removeClass() {
var element = document.getElementById("my-element");
element.classList.remove("my-class-2");
}
As we can see we need to get element, in this case we use:
document.getElementById('element-id')
method.
After that we call:
element.classList.remove("class-name-to-remove")
to remove the the class dynamically from our element. That's all.
Full runnable code example:
// ONLINE-RUNNER:browser;
<!doctype html>
<html lang="en">
<head>
<style>
.my-class-1 {
border: 3px solid red;
padding: 5px;
width: 200px;
}
.my-class-2 {
background: yellow;
}
</style>
<script>
function removeClass() {
var element = document.getElementById("my-element");
element.classList.remove("my-class-2");
}
</script>
</head>
<body>
<div class="my-class-1 my-class-2" id="my-element">
Some text
</div>
<button onclick="removeClass()" style="margin-top: 20px;">
Click this button to remove class from element
</button>
</body>
</html>
Based on this answer I created wiki article for future references:
0 comments
Add comment