Alexander Barac Alexander Barac - 2 months ago 4
Javascript Question

Fixing compile this to undefined?

My app.js is written in es6 standard and my question is >
How can I use code like this?:

$('img').each(() => {
var title = $(this).attr('src');
titles.push(title);
});


I observed that node compile this code to:

'use strict';

$('img').each(function () {
var title = $(undefined).attr('src');
titles.push(title);
});


compile 'this' to 'undefined', how can I fix that?
thx in advance ;)

Answer

Another solution is to use the element passed to the callback, as defined in the .each documentation - Function ( Integer index, Element element ):

var titles = [];

$('img').each((index, element) => {
    var title = $(element).attr('src');
    titles.push(title);
});

document.getElementById('demo').innerHTML = JSON.stringify(titles, undefined, 4);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<img src="http://38.media.tumblr.com/avatar_502c67b98956_64.png">

<img src="https://s-media-cache-ak0.pinimg.com/favicons/62c7e8f531e824f6f8da34453cdd698a8856f3aea36118408c3e5c09.png?9e884f0299eee37aedab60fe1ed363b5">

<pre id="demo"></pre>

Comments