Element className Property - get the class name of an element: - Javascript DOM

Javascript examples for DOM:Element className

Description

Element className Property - get the class name of an element:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<style>
.mystyle {// w  w  w .  j av  a 2s  . c o m
    width: 300px;
    height: 100px;
    background-color: coral;
    color: white;
    margin-bottom: 10px;
}
</style>
</head>
<body>

<div id="myDIV" class="mystyle">
I am a DIV element with class="mystyle"
</div>

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

<p id="demo"></p>

<script>
function myFunction() {
    var x = document.getElementsByClassName("mystyle")[0].className;
    var y = document.getElementById("myDIV").className;
    document.getElementById("demo").innerHTML = "Using getElementsByClassName: " + x + "<br>" + "Using getElementById: " + y;
}
</script>

</body>
</html>

Related Tutorials