How to add / remove CSS class dynamically in jQuery
Published: May 15, 2010 , Updated: May 31, 2011 , Author: mkyong
jQuery comes with addClass() and removeClass() to add or remove CSS class dynamically. For example,
- $(‘#para1′).addClass(‘highlight’); – Add a “highlight’ css class to elements that contain id of “para1″.
- $(‘#para1′).removeClass(‘highlight’); – Remove a “highlight’ css class from elements that contain id of “para1″.
Example
<html> <head> <style type="text/css"> .highlight { background:green; } </style> <script type="text/javascript" src="jquery-1.3.2.min.js"></script> </head> <body> <h1>jQuery add / remove css class example</h1> <p id="para1">This is paragraph 1</p> <p>This is paragraph 2</p> <p>This is paragraph 3</p> <p>This is paragraph 4</p> <button id="addClass">Add highlight</button> <button id="removeClass">Remove highlight</button> <script type="text/javascript"> $("#addClass").click(function () { $('#para1').addClass('highlight'); }); $("#removeClass").click(function () { $('#para1').removeClass('highlight'); }); </script> </body> </html>
Note : You can find more similar articles at - jQuery Tutorials








Hi Mkyong,
I come from china.My English is bad, please forgive me, i found a mistake ,Punctuation display problems?in the paragraph first,you have a mistake, example:
$(‘#para1?).addClass();
$(‘#para1?).addClass();
you can see?
Thanks for your typo report, article is updated. Appreciated your help.
Hi Mkyong,
At the first?there has a mistake?
the first and second is equal?
Sorry, i don’t get you.