Element className Property - Toggle between two class names. - Javascript DOM

Javascript examples for DOM:Element className

Description

Element className Property - Toggle between two class names.

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {//from   w w  w  . ja  va 2s  .  co m
    background-color: aqua;
    padding: 30px;
}

.mystyle2 {
    background-color: coral;
    padding: 50px;
}
</style>
</head>
<body>

<button onclick="myFunction()">Test</button>

<div id="myDIV" class="mystyle">
I am a DIV element
</div>

<script>
function myFunction() {
    var x = document.getElementById("myDIV");
    if (x.className === "mystyle") {
        x.className = "mystyle2";
    } else {
        x.className = "mystyle";
    }
}
</script>

</body>
</html>

Related Tutorials