Javascript Document Object Modeling provides the functionality to change the CSS style class name of the HTML div tag dynamically. Javascript change style class of Div tag function allows you to sets the new class name of the class attribute of Div tag dynamically. You can access the HTML div element using document.getElementById method to change the CSS classname property of the Div tag.
Example of Javascript Change Style Class of Div tag
<html>
<head>
<title>Javascript Change CSS Class of Div tag</title>
<style type="text/css">
.redText, .blueText {
width: 200px;
font-family: Arial;
}
.redText {
color: red;
}
.blueText {
color: blue;
}
</style>
<script
language="javascript"
type="text/javascript">
<![CDATA[
function changeCssClass(objDivID) {
if (document.getElementById(objDivID).className == 'redText') {
document.getElementById(objDivID).className = 'blueText';
}
else {
document.getElementById(objDivID).className = 'redText';
}
}
]]>
</script>
</head>
<body>
<center>
<div
id="div1"
class="redText">
By default text indside this HTML div tag is red. Javascript function will change
the CSS class<br />
of this Div tag and
<br />
text color will change to blue dynamically.
</div>
<br />
<input type="button"
value="click here"
onclick="changeCssClass('div1')" />
</center>
</body>
</html>
Above Javascript DOM example changes the class of HTML div tag onclick event of input button control of HTML. Javascript change Css Class function takes the parameter as id of the div tag whose style class is to be changed. It performs the toggle function to change the class of Div tag and reverts back to the default class name when user clicks the button second time. You can embed the CSS style code inside the Head section of the HTML document using HTML style tag as shown in the above sample code.
Continue to next tutorial: Javascript Change Background Color Style to learn how to change the background color of HTML Div element dynamically.