How to use class attribute functions in Jquery?
In this article I am going to explain about how to use and what is the use of class attribute functions in Jquery. We have four class attribute functions in Jquery.Using those function we can add,remove,check and toggle the class attribute of HTML element(s).
In Jquery we have four class attribute function. Using those functions we can play with class attribute of a HTML element(s). Those are
1.addClass()
2.hasClass()
3.removeClass()
4.toggleClass()1.addClass():
This function is used for add a class to a particular Html element(s).
Example
Html
<div id="shiva">this is shiva</div>
<div>this is normal shiva</div>
Jquery code
$(document).ready(function()
{
$('#shiva').addClass("active");
//then Html will be
//<div id="shiva" calss="active">this is shiva</div>
$('div').addClass("active");
//then Html will be
//<div id="shiva" calss="active">this is shiva</div>
//<div calss="active">this is normal shiva</div>
});2.hasClass():
This function is used for check the condition for an element of a class is exists or not. if class exists it returns true else false
Example
Html
<div id="shiva" class="active">this is shiva</div>
Jquery code
$(document).ready(function()
{
var obj= $('#shiva').hasClass("active");
alert(obj);//true will be altered
});3.removeClass():
This function is used for remove the class from an element. if class exists it removes that class
Example
Html
<div id="shiva" class="active">this is shiva</div>
Jquery code
$(document).ready(function()
{
$('#shiva').removeClass("active");
//then Html will be
//<div id="shiva" >this is shiva</div>
});4.toggleClass():
This function is used for toggle the class from an element. if class exists it removes that class and if class not exists it will add that class. it very use full function
Example
Html
<div id="shiva" class="active">this is shiva</div>
<div id="kumar" >this is shiva</div>
Jquery code
$(document).ready(function()
{
$('#shiva').toggleClass("active");
//then Html will be
//<div id="shiva" >this is shiva</div>
$('#kumar').toggleClass("active");
//then Html will be
//<div id="kumar" class="active">this is shiva</div>
});