How to add class to an element without addClass() method in jQuery ?
The task is to add a new class to the element without using addClass() method with the help of jQuery. There are two approaches that are discussed below:
Approach 1: To perform the operation, we can use toggleClass() method to toggle the class which we want to add to the element.
-
Example:
<!DOCTYPE HTML>
< html >
< head >
< title >
How to add class to an element without
addClass() method in jQuery ?
</ title >
< script src =
</ script >
< style >
#el {
background: green;
}
.newClass {
color: white;
}
</ style >
</ head >
< body style = "text-align:center;" >
< h1 style = "color:green;" >
GeeksForGeeks
</ h1 >
< p id = "GFG_UP" ></ p >
< p id = "el" >This is the element</ p >
< button onclick = "GFG_Fun()" >
Click Here
</ button >
< p id = "GFG_DOWN" ></ p >
< script >
var el_up = document.getElementById('GFG_UP');
var el_down = document.getElementById('GFG_DOWN');
el_up.innerHTML = "Click on the button to "
+ "perform the operation.";
function GFG_Fun() {
$('#el').toggleClass('newClass');
el_down.innerHTML = "Class has been added";
}
</ script >
</ body >
</ html >
|
-
Output:
Approach 2: We can also use attr() method and prop() method to add a new attribute ‘class’ to the element.
-
Example:
<!DOCTYPE HTML>
< html >
< head >
< title >
How to add class to an element without
addClass() method in jQuery ?
</ title >
< script src =
</ script >
< style >
#el {
background: green;
}
.newClass {
color: white;
}
</ style >
</ head >
< body style = "text-align:center;" >
< h1 style = "color:green;" >
GeeksForGeeks
</ h1 >
< p id = "GFG_UP" ></ p >
< p id = "el" >This is the element</ p >
< button onclick = "GFG_Fun()" >
Click Here
</ button >
< p id = "GFG_DOWN" ></ p >
< script >
var el_up = document.getElementById('GFG_UP');
var el_down = document.getElementById('GFG_DOWN');
el_up.innerHTML = "Click on the button to "
+ "perform the operation.";
function GFG_Fun() {
$('#el').attr('class', 'newClass');
el_down.innerHTML = "Class has been added";
}
</ script >
</ body >
</ html >
|
-
Output:
Last Updated :
24 Apr, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...