Search code examples
javascriptjquerychaining

How this code works? (jQuery chaining)


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

In the code you can see that the filter() returns an object, which contains a collection of the "filtered" objects. and the append() 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 + ")";
});

Solution

  • 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.