yossi yossi - 1 year ago 91
jQuery Question

How this code works? (jQuery chaining)

I got this code from the jQuery plugin tutorial. however, my question is a


In the code you can see that the
returns an object, which contains a collection of the "filtered" objects. and the
is manipulating it.

What i ask is: how the append function manipulates ALL of the elements and not working only once on the returned object?

this.filter( "a" ).append(function() {
return " (" + this.href + ")";

Answer Source

This is due to the nature of append.function() and the difference in scope between the initial this and the one inside the function in your code.

Per the jQuery documentation at http://api.jquery.com/append/#append-function, append.function() operates on "each element in the set of matched elements. [...] Within the function, this refers to the current element in the set."

So, in your code, this.filter("a") is a jQuery object containing any matching elements, while this.href within the function itself represents each of those elements in turn during the iteration through the collection. Hence, the text is appended to all of the matching elements.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download