Add multiple classes jquery – You can separate multiple classes with the space: like as $(“p”).addClass(“class1 class2 class3”); Jquery addclass() is used to add one or multiple classes dynamically to the selected element.
The jQuery addClass() method adds one or more classes to the selected elements.
$("p").addClass("myClass yourClass");
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
<style>
.color {<br />
color: red;<br />
}<br />
.fontWeight {<br />
font-weight: bold;<br />
}<br />
</style>
<h2 style="color: red;">Pakainfo</h2>
<button>
click here
</button>
<script>
$('#Pakainfo_UP').text("Click on button to add multiple"
+ " classes to this element");
function Pakainfo_Data() {
$("#Pakainfo_UP").addClass("color fontWeight");
$('#Pakainfo_DOWN').text("color and fontWeight,"
+ " Both classes added");
}
</script>
$(document).ready(function(){
$('.elementclass').addClass('first_cls');
//OR
$('.elementclass').addClass('first_cls').addClass('second_cls_name');
}
separated by a space
$(document).ready(function(){
$( "div" ).addClass( "firstCls SecondCls" );
$( "div" ).addClass( "firstCls SecondCls ThirdCls FourthCls" );
})
<script>
$( "div" ).addClass(function( index, class ) {
var addedClass;
if ( class === "pink" ) {
addedClass = "green";
$( "p" ).text( "There is one green div" );
}
return addedClass;
});
</script>
You can add multiple classes to an element in JavaScript by using the classList property of the element. The classList property provides methods to add, remove, toggle, and check if a class exists on an element.
To add multiple classes, you can use the add() method of the classList property and pass in the class names as separate arguments. Here’s an example:
// Get the element you want to add classes to
const element = document.getElementById('my-element');
// Add multiple classes to the element
element.classList.add('class1', 'class2', 'class3');
In this example, the add() method is used to add three classes, class1, class2, and class3, to the element with the ID my-element.
You can also add classes dynamically based on conditions or user interactions. For example:
// Get the element you want to add classes to
const element = document.getElementById('my-element');
// Add a class based on a condition
if (someCondition) {
element.classList.add('my-class');
}
// Add a class on click
element.addEventListener('click', function() {
element.classList.add('clicked');
});
In these examples, a class is added to the element based on a condition or a user click event using the classList property’s add() method.