$ (this) is null inside .click (function () {...}), why?

I have this jquery code that allows me to click the link to retrieve the parent element and change the value elsewhere:

$("a.menu_filter_select").click(function(){ var parent_filter = $(this).parent("tr"); // Update value parent_filter.find(".filter_value").html($(this).html()); }); 

The problem is that it gets null on $ (this), which is an unexpected behavior, I don’t understand why this is not working, any idea?

Here is console debugging with a breakpoint inside the method:

 $(this) > null this > <a class=​"menu_filter_select" href=​"http:​/​/​localhost:​3000/​#" rel=​"1">​test</a>​ 
+4
source share
4 answers

I think because your function receives the event as an argument, and you need event.target.

 $('a.menu_filter_select').click(function(evt) { var parent_filter = $(evt.target).closest('tr'); 

I also recommend using closest instead of parent , as your code will work even if someone puts <b> , <i> or <span> around the anchor. I also use find instead of child .

Edit: In fact, this in FireFox refers to a binding object, but I cannot be sure that it is implemented in the same way in other browsers. BUT event.target can refer to a child if, say, a document looks like this:

 <a><b>some text</b> other text</a> 

then this event handler can output various elements:

 $(a).click(function(event) { console.log(this, event.target); }); 

Try to run this code in FireBug, see how it works.

+4
source

The only reason I can think that this will happen is because the identifier $ was overridden.

You can check if $ == jQuery in the function. If this is not the case, then you probably included another script that also uses the identifier $ .

There is a compatibility mode for jQuery that will be used if there is another library that also uses this identifier, where it returns the value of the identifier $ to its original value, and instead you use the jQuery identifier.

+2
source

Sometimes the binding between $ and jQuery may fail, try replacing $ with jQuery.

Also try using $ .log instead of a breakpoint to ensure that the scope of this does not change.

0
source

Personally, I always use $ when using jquery, but I saw that this happened when I turned on the plugin that used jquery, not $. For some reason, I don’t like to use both, but just changing jquery to $ in the plugin code is sorted for me.

0
source

All Articles