Javascript DOM HTML Element classList Property search for a class name

Introduction

Find out if an element has a "mystyle" class:

var x = document.getElementById("myDIV").classList.contains("mystyle");

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

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {/*from w w  w.  ja  va  2s.co  m*/
  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").classList.contains("mystyle");
  document.getElementById("demo").innerHTML = x;
}
</script>

</body>
</html>



PreviousNext

Related