Skip to content

Instantly share code, notes, and snippets.

@amelieykw
Last active April 10, 2018 15:12
Show Gist options
  • Save amelieykw/62dda6dfe2a3877e69cdc9c37535e099 to your computer and use it in GitHub Desktop.
Save amelieykw/62dda6dfe2a3877e69cdc9c37535e099 to your computer and use it in GitHub Desktop.
[CSS - Add/Remove Class] #CSS #HTML #addClass #removeClass

Step 1) Add HTML :

<button onclick="myFunction()">Try it</button>

<div id="myDIV">
  This is a DIV element.
</div>

Step 2) Add CSS :

.mystyle {
    width: 100%;
    padding: 25px;
    background-color: coral;
    color: white;
    font-size: 25px;
}

Step 3) Add JavaScript :

function myFunction() {
    var element = document.getElementById("myDIV");
    element.classList.add("mystyle");
}

Cross-browser solution :

Note: The classList property is not supported in Internet Explorer 9. The following code will work in all browsers:

function myFunction() {
    var element, name, arr;
    element = document.getElementById("myDIV");
    name = "mystyle";
    arr = element.className.split(" ");
    if (arr.indexOf(name) == -1) {
        element.className += " " + name;
    }
}

Step 1) Add HTML :

<button onclick="myFunction()">Try it</button>

<div id="myDIV" class="mystyle">
  This is a DIV element.
</div>

Step 2) Add CSS:

.mystyle {
    width: 100%;
    padding: 25px;
    background-color: coral;
    color: white;
    font-size: 25px;
}

Step 3) Add JavaScript:

function myFunction() {
    var element = document.getElementById("myDIV");
    element.classList.remove("mystyle");
}

Cross-browser solution :

Note: The classList property is not supported in Internet Explorer 9. The following code will work in all browsers:

function myFunction() {
    var element = document.getElementById("myDIV");
    element.className = element.className.replace(/\bmystyle\b/g, "");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment