The addClass method

The addClass method adds the specified CSS class to an element.

Syntax

One CSS class:

javascript$(selector).addClass(CSS class name);

Several CSS classes (in a row):

javascript$(selector).addClass('class1 class2 class3 ...');

Several CSS classes (array):

javascript$(selector).addClass(['class1', 'class2', 'class3', '...']);

Applying a function to each element in a set:

javascript$(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:

html<p id="test">text</p>
javascript$('#test').addClass('www');

HTML the code will look like this:

html<p id="test" class="www">text</p>

Example

Our paragraph already has a class. Let's add the www class to it:

html<p id="test" class="eee">text</p>
javascript$('#test').addClass('www');

HTML the code will look like this:

html<p id="test" class="eee www">text</p>

Example

Our paragraph already has two classes. Let's add the www class to it:

html<p id="test" class="eee ggg">text</p>
javascript$('#test').addClass('www');

HTML the code will look like this:

html<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:

html<p id="test" class="eee">text</p>
javascript$('#test').addClass('www ggg');

HTML the code will look like this:

html<p id="test" class="eee www ggg">text</p>

See also