Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery addClass() not working with event.target

Tags:

Please help.

Why is the jquery addClass() not working with event.target? I have made a code and it supposed to add class on the target when clicked, but it does not work, and it says,e.target.addClass is not a function.

http://jsfiddle.net/Lq9G4/

CODE:

<html lang="en"> <head>     <meta charset="UTF-8">     <title>Class Test</title>     <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>     <style>         .big {             font-size: 5em;         }         .small {             font-size: 1em;         }     </style>  </head> <body>     <p>This is the text</p>     <script>         $(function() {             $("p").click(function(e) {                         $("a").removeClass("big").addClass("small");                       $("this").addClass("big"); //This doesn't work                       e.target.addClass("big"); //nor this one                                     });         });      </script> </body> </html> 
like image 809
qtgye Avatar asked Apr 22 '14 05:04

qtgye


People also ask

What does addClass do in jQuery?

The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.

How do you check class is exists in jQuery?

jQuery hasClass() Method The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".


2 Answers

Basically e.target will be a javascript object, you have to convert it into a Jquery object before utilizing its functions like .addClass()

Try,

$(e.target).addClass("big");  

and at the same time, $("this").addClass("big"); this code will not work since you are passing this as a string. this also a javascript object, you need to convert that too as a jquery object like $(this)

like image 61
Rajaprabhu Aravindasamy Avatar answered Sep 25 '22 13:09

Rajaprabhu Aravindasamy


You have two problem:

$(this).addClass("big"); //Unquote to "this" $(e.target).addClass("big"); // select e.target with $() wrapper. 
like image 27
Bhojendra Rauniyar Avatar answered Sep 22 '22 13:09

Bhojendra Rauniyar