-3

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 + ")";
});
yossi
  • 3,090
  • 7
  • 45
  • 65
  • 2
    You're question doesn't make much sense. In the second paragraph you said the return object contains the collection … so "ALL of the elements" and "the returned object" are the same thing. – Quentin Jun 19 '16 at 09:04
  • i understand.. i'll try to rephrase. – yossi Jun 19 '16 at 09:24
  • 1
    If I've understood what you're asking (literally how it works), it's a question of scope. Per the docs - 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." In other words, in your code, the scope of the initial `this.filter` is different to that of `this.href` within the function itself, which represents each element in turn during the iteration through the collection. – fridge_light Jun 19 '16 at 09:39
  • thank you @fridge_light - seems you understood what i asked. and answered it. thanks again. (please add it as an answer) – yossi Jun 19 '16 at 11:43

1 Answers1

1

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.

fridge_light
  • 436
  • 1
  • 3
  • 7