"this" does not work as expected

I struggled with this for an hour, and I cannot solve it. I am new to using this in javascript, but it is very simple and it just doesn't work.

Here is the HTML

 <ul class="nav pull-right nav-tabs" id="primarynav"> <li class=" navlink"> <a href="#">About</a> </li> <li class="navlink active"> <a href="#">Portfolio</a> </li> <li class="navlink"> <a href="#">Contact</a> </li> </ul> 

And js

 $(document).ready(function(){ $(".navlink").click(function(){ $(".navlink").removeClass("active"); this.addClass("active"); }); }); 

Thus, it must remove the active class from all elements with the navlink class, and then add the active class to the clicked element. But this is not so.

http://jsfiddle.net/Tckf7/

+4
source share
5 answers

Change it to:

 $(this).addClass("active"); 

JsFiddle example

.addClass() is a jQuery method, and you tried to apply it to an object other than jQuery ( this vs $(this) ).

+10
source

addClass () is a jQuery method, but this is a direct reference to a DOM object. Before using the jQuery method, you need to wrap this in a jQuery object.

 $(document).ready(function(){ $(".navlink").click(function(){ $(".navlink").removeClass("active"); $(this).addClass("active"); }); }); 

DEMO - using $(this).addClass() instead of this.addClass()


Edit

Think a little about it. You can never call the jQuery addClass() method on a JavaScript object, because addClass() is a jQuery method.

To do the same in pure JavaScript, if you just want to use this , you can use element.className , similar to this:

 $(document).ready(function(){ $(".navlink").click(function(){ $(".navlink").removeClass("active"); //$(this).addClass("active"); this.className += " active"; }); }); 

DEMO - Using this.className example


Although, if you are using jQuery already, it makes no sense not to use $(this).addClass() instead.

+2
source

this refers to the DOMElement to which jQuery has attached an event. To turn it into a jQuery collection and be able to use jQuery methods like addClass , pass it as the $ argument:

 $(this).addClass("active"); 

Inside the function, the this actually refers to the context of the function. In the case of event handlers, the context is the DOMElement to which the handler is bound.

+2
source

this not a jQuery object, use $(this) instead.

+1
source

You should use $ (this)

 $(document).ready(function(){ $(".navlink").click(function(){ $(".navlink").removeClass("active"); $(this).addClass("active"); }); }); 

http://jsfiddle.net/Tckf7/2/

+1
source

Source: https://habr.com/ru/post/1469342/


All Articles