Alexander Barac Alexander Barac - 1 year ago 66
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');

I observed that node compile this code to:

'use strict';

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

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

Answer Source

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');

document.getElementById('demo').innerHTML = JSON.stringify(titles, undefined, 4);
<script src=""></script>

<img src="">

<img src="">

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download