Javascript DOM HTML Element className Property check class name

Introduction

In this example, we first search for the element in the document with id="myDIV".

Then, if this element has a class of "mystyle" - change its font size.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {/*from   ww  w  .j  a  va  2 s.  co  m*/
  width: 300px;
  height: 50px;
  text-align: center;
  background-color: gray;
  color: white;
  margin-bottom: 10px;
}
</style>
</head>
<body>
<div id="myDIV" class="mystyle">
I am a DIV element
</div>

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

<script>
function myFunction() {
  var x = document.getElementById("myDIV");

  if (x.className === "mystyle") {
    x.style.fontSize = "30px";
  }
}
</script>

</body>
</html>



PreviousNext

Related