- Back to Home »
- JavaScript »
- Javascript Part-6 changing css class using js code if condition
Posted by :
Sudhir Chekuri
Sunday, 27 October 2013
In this example i wrote two css classes cssclass1 and cssclass2.
when page is loaded cssclass1 styles is applied to the div1 tag and when user click on the button cssclass2 is applied to div tag using javascript.
js code to change css class of div tag
<!DOCTYPE html>
<html>
<head>
<style type="text/css" >
.cssclass1
{
width:200px;
height:200px;
background-color:yellow;
}
.cssclass2
{
width:200px;
height:200px;
background-color:green;
}
</style>
<script language="javascript">
function f1() {
var css = document.getElementById("div1").className;
if (css == "cssclass1") {
document.getElementById("div1").className = "cssclass2";
} else { document.getElementById("div1").className = "cssclass1"; }
}
</script>
</head>
<body>
<div id="div1" class="cssclass2" >Text inside div tag</div>
<input type="button" value="Submit" onclick="f1()">
</body>
</html>
when page is loaded cssclass1 styles is applied to the div1 tag and when user click on the button cssclass2 is applied to div tag using javascript.
js code to change css class of div tag
<!DOCTYPE html>
<html>
<head>
<style type="text/css" >
.cssclass1
{
width:200px;
height:200px;
background-color:yellow;
}
.cssclass2
{
width:200px;
height:200px;
background-color:green;
}
</style>
<script language="javascript">
function f1() {
var css = document.getElementById("div1").className;
if (css == "cssclass1") {
document.getElementById("div1").className = "cssclass2";
} else { document.getElementById("div1").className = "cssclass1"; }
}
</script>
</head>
<body>
<div id="div1" class="cssclass2" >Text inside div tag</div>
<input type="button" value="Submit" onclick="f1()">
</body>
</html>