Languages

JavaScript - how to remove class from div

6 points
Asked by:
Kate_C
2860

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 answers
5 points
Answered by:
Kate_C
2860

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
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.