Handling CSS by using jQuery
DescriptionH...
Description
Handle CSS using jQuery/Javascript Here are two alternatives. In jQuery, you may use attr method to set attribute values of selected elements. In JavaScript, you may use className property to do the same thing.Code
<html>
<head>
<title>Handle CSS using jQuery/Javascript</title>
<script src="jquery-1.7.1.min.js"></script>
<style type="text/css">
table {background-color:gray;}
div {font-weight:bold;color:#ffffff;height:50px;width:170px;border:solid 2px #ffffff;}
.classBLUE {background-color:#0000ff;color:#ffffff;}
.classRED {background-color:#ff0000;color:#ffffff;}
.classGREEN {background-color:#00cc00;color:#ffffff;}
</style>
<script type="text/javascript">
function setGreenjQuery()
{
$("#divRGB").attr("class", "classGREEN");
}
function setBluejQuery()
{
$("#divRGB").attr("class", "classBLUE");
}
function setRedjQuery()
{
$("#divRGB").attr("class", "classRED");
}
function setGreenJs()
{
document.getElementById("divRGB").className = 'classGREEN';
}
function setBlueJs()
{
document.getElementById("divRGB").className = 'classBLUE';
}
function setRedJs()
{
document.getElementById("divRGB").className = 'classRED';
}
</script>
</head>
<body>
<table width="170px">
<tr>
<td colspan="3" align="center">
<div id="divRGB">Handle CSS</div>
</td>
</tr>
<tr>
<td colspan="3" align="center">By jQuery</td>
</tr>
<tr>
<td><input type="button" value="Red" onclick="setRedjQuery()"/></td>
<td><input type="button" value="Green" onclick="setGreenjQuery()"/></td>
<td><input type="button" value="Blue" onclick="setBluejQuery()"/></td>
</tr>
<tr>
<td colspan="3" align="center">By Javascript</td>
</tr>
<tr>
<td><input type="button" value="Red" onclick="setRedJs()"/></td>
<td><input type="button" value="Green" onclick="setGreenJs()"/></td>
<td><input type="button" value="Blue" onclick="setBlueJs()"/></td>
</tr>
</table>
</body>
</html>
Browser Compatibility
I have tested this code in the following Web browsers:- Internet Explorer
- Mozilla Firefox
- Google Chrome
- Safari
- Opera
Further Reading
- Download the latest jQuery - http://jquery.com/[^]
- jQuery Tutorial - http://www.w3schools.com/jquery/default.asp[^]