Javascript DOM HTML Element classList Property remove class name if exist

Introduction

Find out if an element has a "mystyle" class. If so, remove another class name:

Click the button to find out if the DIV element has a class of "mystyle".

If so, remove "anotherClass".

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {//  w  ww  . ja  v  a 2s.  c om
  width: 500px;
  height: 50px;
  border: 1px solid black;
}

.anotherClass {
  background-color: lightblue;
  padding: 25px;
}

.thirdClass {
  text-align: center;
  font-size: 25px;
  color: navy;
  margin-bottom: 10px;
}
</style>
</head>
<body>
<div id="myDIV" class="mystyle anotherClass thirdClass">
I am a DIV element
</div>

<button onclick="myFunction()">Test</button>
<p id="demo"></p>
<script>
function myFunction() {
  var x = document.getElementById("myDIV");

  if (x.classList.contains("mystyle")) {
    x.classList.remove("anotherClass");
  } else {
    document.getElementById("demo").innerHTML = "Could not find it.";
  }
}
</script>

</body>
</html>



PreviousNext

Related