Javascript DOM HTML Element classList Property toggle between two classes

Introduction

Toggle between two classes for a <div> element:

document.getElementById("myDIV").classList.toggle("newClassName");

Click the button to toggle between two classes.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {//from   www .  j  av a 2  s . c om
  width: 300px;
  height: 50px;
  background-color: coral;
  color: white;
  font-size: 25px;
}

.newClassName {
  width: 400px;
  height: 100px;
  background-color: lightblue;
  text-align: center;
  font-size: 25px;
  color: navy;
  margin-bottom: 10px;
}
</style>
</head>
<body>
<button onclick="myFunction()">Test</button>

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

<script>
function myFunction() {
  document.getElementById("myDIV").classList.toggle("newClassName");
}
</script>

</body>
</html>



PreviousNext

Related