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>   Â<scriptsrc=   Â</script>   Â<style>       Â#el {           Âbackground: green;       Â}       Â.newClass {           Âcolor: white;       Â}   Â</style></head>ÂÂ<bodystyle="text-align:center;">   Â<h1style="color:green;">       ÂGeeksForGeeks   Â</h1>   Â<pid="GFG_UP"></p>   Â<pid="el">This is the element</p>   Â<buttononclick="GFG_Fun()">       ÂClick Here   Â</button>   Â<pid="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>   Â<scriptsrc=   Â</script>   Â<style>       Â#el {           Âbackground: green;       Â}       Â.newClass {           Âcolor: white;       Â}   Â</style></head>ÂÂ<bodystyle="text-align:center;">   Â<h1style="color:green;">       ÂGeeksForGeeks   Â</h1>    Â   Â<pid="GFG_UP"></p>   Â<pid="el">This is the element</p>    Â   Â<buttononclick="GFG_Fun()">       ÂClick Here   Â</button>    Â   Â<pid="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:
