Ortal
Ortal

Reputation: 343

jQuery chaining - why cant I chain this?

Im having an issue with chaining. For example, the following will work

$('#myActivityFeed .bv_default_player_pic').attr("src", url);
$('#myActivityFeed. bv_default_player_pic').removeClass().addClass('badge');

yet the following will not:

$('#myActivityFeed .bv_default_player_pic').attr("src", url).removeClass().addClass('badge');

as far as I know, you should be able to chain these events.... any thoughts as to why I cannot?

Upvotes: 2

Views: 5235

Answers (4)

T.J. Crowder
T.J. Crowder

Reputation: 1075885

Your example should work. Here's a live example. It shows my Gravatar with a red border around it via class "bv_default_player_pic", inside a div with the id value "myActivityFeed". When you click the button, it executes your code (unchanged, literally copied-and-pasted):

$('#myActivityFeed .bv_default_player_pic').attr("src", url).removeClass().addClass('badge');

...which sets the src to be your Gravatar, removes all classes, and adds class "badge" (making the border black, with my CSS).

Works just fine. The problem lies elsewhere (is url defined?).

Upvotes: 2

Jose Faeti
Jose Faeti

Reputation: 12314

According to the latest jQuery version, There is no need to pass a parameter to the removeClass() method.

This example illustrate the above code should be chainable and working even without any parameter passed to removeClass().

From the jQuery removeClass() docs.

If a class name is included as a parameter, then only that class will be removed from the set of matched elements. If no class names are specified in the parameter, all classes will be removed.

The only issue I can see in your code is that the variable url may be undefined.

Upvotes: 2

Ferruccio
Ferruccio

Reputation: 100748

removeClass() with no parameters removes all classes, so why not do this:

$('#myActivityFeed .bv_default_player_pic').attr("src", url).attr("class", "badge");

Upvotes: 0

Arindam
Arindam

Reputation: 998

The attr method does not return a jQuery object. Check here. attr Api.

Hence you cannot put anything to its end.

Whereas removeClass returns a jQuery object. Check here removeClass api, to which you can continue applying methods of jQuery

Upvotes: -1

Related Questions