Javascript DOM HTML Element className Property toggle class name

Introduction

Toggle between two class names.

Click the button multiple times to toggle between two class names for DIV.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {/*from w  ww.  j  a  va  2 s  .  c  om*/
  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>



PreviousNext

Related