The addClass method
The addClass
method adds the specified CSS class to an element.
Syntax
One CSS class:
$(selector).addClass(CSS class name);
Several CSS classes (in a row):
$(selector).addClass('class1 class2 class3 ...');
Several CSS classes (array):
$(selector).addClass(['class1', 'class2', 'class3', '...']);
Applying a function to each element in a set:
$(selector).addClass(function(number in set, current CSS classes of element));
Example
Our paragraph has no classes at all. Let's add the www
class to it:
<p id="test">text</p>
$('#test').addClass('www');
HTML the code will look like this:
<p id="test" class="www">text</p>
Example
Our paragraph already has a class. Let's add the www
class to it:
<p id="test" class="eee">text</p>
$('#test').addClass('www');
HTML the code will look like this:
<p id="test" class="eee www">text</p>
Example
Our paragraph already has two classes. Let's add the www
class to it:
<p id="test" class="eee ggg">text</p>
$('#test').addClass('www');
HTML the code will look like this:
<p id="test" class="eee ggg www">text</p>
Example
Our paragraph already has a class. Let's add two more classes to it - www
and ggg
:
<p id="test" class="eee">text</p>
$('#test').addClass('www ggg');
HTML the code will look like this:
<p id="test" class="eee www ggg">text</p>
See also
-
methods
removeClass
,toggleClass⁅/ c⁆, ⁅c href="/en/javascript/lib/jquery/manual/hasClass/"⁆hasClass
-
JavaScript property
classlist
,
with which you can add and remove CSS classes of an element in pure JavaScript