Search code examples
javascriptjqueryecmascript-6babeljs

jQuery .each() function with ES6 arrow functions


I have this ES6 code, after I compile it with Babel to ES5 the this inside .each's call back becomes undefined. How do I fix this problem?

let mediaBoxes = $(".now-thumbnail");
let titles = [];
mediaBoxes.each(() => {
      let obj = {
              index: i,
              title: $(this).find(".now-thumbnail-bottomtext").text().trim()
           };
  titles.push(obj);
});

Solution

  • My solution is to not use this at all, but use the variables that are passed to the callback function. The first one is the index and the second one gives you the DOM element itself.

    let mediaBoxes = $('.now-thumbnail');
    let titles = [];
    mediaBoxes.each((index, element) => {
      let obj = {
        index: index,
        title: $(element).find('.now-thumbnail-bottomtext').text().trim(),
      };
      titles.push(obj);
    });