1

New to ES6. Trying to grab data attribute of clicked link. HTML:

<ul class="home-news-slider-categories">
  <li><a href="#" data-slide="1">Slide 1</a><li>
  <li><a href="#" data-slide="2">Slide 2</a><li>
  ...
</ul>

In my JS, I've written a test function to grab the slide data attribute on a given item when clicked:

$('.home-news-slider-categories > li > a').click((e) => {
  console.log($(this).data('slide'));
  e.preventDefault();
});

The event is being fired whenever I click a link, but the console is returning undefined each time.

Am I using $(this) incorrectly?

psorensen
  • 809
  • 4
  • 17
  • 33
  • 1
    Use standard function notation instead of arrow function notation. The latter does not alter the `this` context. – trincot Jan 13 '17 at 19:49
  • 1
    Exactly, you can also use e.targetElement to know which element was clicked instead of changing, this. – Joel Harkes Jan 13 '17 at 19:50
  • 1
    If you console.log $(this) inside your jQuery function, you'll see the problem. $(this) isn't an a link element, like you're expecting it to be. – devlin carnate Jan 13 '17 at 19:52

0 Answers0