Element className Property - To add a class to an element, without overwriting existing values - Javascript DOM

Javascript examples for DOM:Element className

Description

Element className Property - To add a class to an element, without overwriting existing values

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {//from   www.ja  va 2  s  .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>

Related Tutorials