Javascript DOM HTML Element className Property append class name

Introduction

To append a class to an element, without overwriting existing values, insert a space and the new class name:

document.getElementById("myDIV").className += " anotherClass";

Click the button to add an additional class to the div element.

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {/*  ww w .ja  v a  2s . c o m*/
  width: 500px;
  height: 50px;
  border: 1px solid black;
  margin-bottom: 10px;
}

.anotherClass {
  background-color: coral;
  text-align: center;
  font-size: 25px;
  color: white;
}
</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 += " anotherClass";
}
</script>

</body>
</html>



PreviousNext

Related