The below code snippet explains how to add or apply CSS class to an HTML control using jQuery
<div class = "myClass1" id = "myDiv"></div>
<input type="button" id="demo" value = "Demo" />
<script type = "text/javascript" src = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js"></script>
<script type="text/javascript">
$("#demo").live("click", function () {
//Get CSS class
var classes = $("#myDiv").attr("class");
alert(classes);
//Remove CSS class
$("#myDiv").addClass("myClass2");
//Get Updated CSS class
var classes = $("#myDiv").attr("class");
alert(classes);
});
</script>
Explanation:
In the above sample, a click event handler has been attached to the HTML button with id “demo”. When the button is clicked the name of the class is fetched using the attr("class") method of jQuery and the class name is displayed in alert box. Then a new class is applied to the control using the addClass("myClass2") method of jQuery and then again the name of class is fetched and now you it displays name of 2 classes “myClass1 myClass2”.