0

I have an example where I use jQuery to get and replace titles attribute of images. ( I change title attribute for the purpose of translation). Here an example, that works, but I can not understand when I may use 'this'. Notice, in the first part I used 'jQuery(this) and in the set part I used jQuery(item) and both work. Why? What's the difference between 'this' and 'item' in this context?

https://codepen.io/capbussat/pen/wvPWRPN?editors=1111

...

var titles = [];

jQuery(".container").find("img").each(function (index, item) {
titles.push(jQuery(this).attr("title"));
console.log("get " + titles[index]);
});

console.log(titles);
titles = ["a", "b"];

jQuery(".container").find("img").each(function (index, item) {
 jQuery(item).attr("title", titles[index]);
     console.log("set " + titles[index]);
  });
document.getElementById("One").setAttribute("title", titles[0]);
console.log(titles);

...

  • 2
    Always read [the documentation](https://api.jquery.com/each/) before posting. As it says there: jQuery calls your callback with `this` set to the same value it provides as the second argument (`item` in your case). More in [this question's answers](https://stackoverflow.com/questions/6377970/jquery-each-this-and-element) which I found with [this search](/search?q=%5Bjquery%5D+each+this). More about searching [here](/help/searching). – T.J. Crowder Mar 22 '22 at 08:57
  • Also read this question and answers: [arrow functions and this](https://stackoverflow.com/a/28798362/2181514) if you want to / start to use `.each((idx, item) =>` – freedomn-m Mar 22 '22 at 09:56
  • Sorry, I really did not find the question that you mention which answers my question. Thanks a lot! – user2088350 Mar 22 '22 at 11:15

0 Answers0