In this blog it is explained how addClass, removeClass and toggleClass method is used in jquery to add or remove class from html element. It is very useful in jquery as it add or remove desired class to any html element dynamically.
- Write simple html which show one text line and three button with three different id’s.
<head>
<title>css classes</title>
</head>
<body>
<p>It is blue color text.<p>
<button id=”b1″>Add blue</button>
<button id=”b2″>Remove blue</button>
<button id=”b3″>Toggle blue</button>
</body>
</html>.
2. Then link css using below code of line.
3. In addclass.css file add following code
{
color:blue;
}
4. Then write javascript as below in head section of html file.
<script>
jQuery(document).ready(function(){
jQuery(“#b1”).click(function(){
jQuery(“p”).addClass(“blue”);
});
jQuery(“#b2”).click(function(){
jQuery(“p”).removeClass(“blue”)
});
jQuery(“#b3”).click(function(){
jQuery(“p”).toggleClass(“blue”);
});
});
</script>
First line of code add jquery library. Third line load jquery when whole page is load.
addclass method
It add class “blue” to p element. when button with id b1 is clicked text within p tag changes to blue color.
removeClass method
It remove class “blue” from p element. when button with id b2 is clicked text within p tag changes from blue to default color.
toggleClass method
It add class to html element if not present and remove class from html element if it is already added.
Final code
<head>
<link rel=”stylesheet” href=”addclass.css”/>
<script src=”jquery.js”></script>
<script>
jQuery(document).ready(function(){
jQuery(“#b1”).click(function(){
jQuery(“p”).addClass(“blue”);
});
jQuery(“#b2”).click(function(){
jQuery(“p”).removeClass(“blue”)
});
jQuery(“#b3”).click(function(){
jQuery(“p”).toggleClass(“blue”);
});
});
</script>
<title>css classes</title>
</head>
<body>
<p>It is blue color text.<p>
<button id=”b1″>Add blue</button>
<button id=”b2″>Remove blue</button>
<button id=”b3″>Toggle blue</button>
</body>
</html>