Javascript DOM HTML Element className Property overwrite an existing class name

Introduction

Overwriting an existing class name with a new one:

Click the button to change the value of the class attribute of DIV to "newClassName".

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {/*from   w w  w  . j  a  v a 2 s.  com*/
  width: 200px;
  height: 50px;
  background-color: coral;
  color: white;
  margin-bottom: 10px;
}

.newClassName {
  width: 400px;
  height: 100px;
  background-color: lightblue;
  text-align: center;
  font-size: 25px;
  color: navy;
  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() {
  document.getElementById("myDIV").className = "newClassName";
}
</script>

</body>
</html>



PreviousNext

Related