jQuery addClass() Attribute

The jQuery addclass() attribute adds one or more classes to the selected element. It adds new class(es) and do not erase the classes that were already set.

$(selector).addclass(classname, function(index, oldclassname)) 

The selector is the element on which class to be added. The selector can be one or more than one element. The classname is the required field. It is one or more classes to be added. The function is an optional parameter. The index receives the index position of the element in the set and the oldclassname returns existing class name of the selected element.

Example - Add single class

<style>
.cls1 { 
font-size: 22px;
}
.cls2 { 
color : red; 
font-style: italic; 
}
</style>

<p class="cls1" id="demo"> 
Hello World!
</p>

<script>
$(document).ready(function(){
$("p#demo").addClass("cls2");
});
</script>

Output of the above code

Hello World!

In the above example, cls2 class name is added to the paragraph.


Example - Add multiple classes

<style>
.cls3 { 
	font-size: 22px;
}
.cls5 { 
	font-style: oblique; 
}
.cls4 { 
	color: green;
}
</style>

<p class="cls3" id="demo1"> 
Hello World!
</p>

<script>
$(document).ready(function(){
$("p#demo1").addClass("cls4 cls5");
});
</script>

Output of the above code

Hello World!

In the above example, both cls4 and cls5 classes are added to the paragraph.



Read more articles


General Knowledge



Learn Popular Language