-1

i have the following html:

  <body>
    <div >
      <h1>OnlineList</h1>
      <ul id="onlineList">
        <li con="123" age="10">Test A</li>
        <li con="234" age="11">Test B</li>
        <li con="345" age="10">Test C</li>
        <li con="456" age="12">Test D</li>
      </ul>
    </div>
  </body>

and i am using jquery as following:

var meow = [];
var meow2 = [];

var a = $("li").each(function () 
    {
      meow.push( $(this).attr("age"));
  });

var b = $("li").each( () =>
    
      meow2.push( $(this).attr("age"))
  );

console.log(meow);
console.log(meow2);

meow will give me the expected output:

["10", "11", "10", "12"] 

meow2 will give me:

[undefined, undefined, undefined, undefined]

I'm little bit suprised what happend cause i just use an anonymous/arrow function?

Trace
  • 51
  • 10
  • 1
    FYI, you are using an anonymous function in both cases. An anonymous function is just a function without a name. It is not synonymous with arrow functions. – Heretic Monkey Feb 04 '21 at 16:08
  • @HereticMonkey sry, you are right! – Trace Feb 04 '21 at 16:14
  • 1
    Aside from the arrow function scope issue, you should be careful using non-standard attributes in your HTML as it can cause JS/CSS problems. In this case I'd suggest using data attributes instead. Also, you can simplify your code by using `map()`: `let meow = $('li').map((i, el) => $(el).data('age')).get();`. A – Rory McCrossan Feb 04 '21 at 16:16

1 Answers1

0

If you use the JS ES6 syntax to declare a function "this" is no longer the calling element. You have to use:

var b = $("li").each( (index, element) =>

  meow2.push( $(element.currentTarget).attr("age"))
);
Thallius
  • 2,482
  • 2
  • 18
  • 36