0

Hi im new into java script and im trying to do a little project to train my skills, but i have a problem with getAttribute and im stuck :) maybe somebody can help me?

(function() {
  var buttons = document.querySelectorAll('.btn');
  buttons.forEach(function(button) {
    button.addEventListener('click', function(e) {
      var emotion = e.target.getAttribute("data-emo");
      console.log(emotion);
    })
  });
})();
<div id="auswahl">
  <button type="button" class="btn" data-emo="happy"> <img src="https://esquilo.io/png/thumb/ejzF8hfbnQpFxzA-Happy-Face-Emoji-PNG-File.png" width="100"> </button>
  <button type="button" class="btn" data-emo="sad"> <img src="https://cdn.shopify.com/s/files/1/1061/1924/products/Very_sad_emoji_icon_png_large.png?v=1571606089" width="100"> </button>
</div>

The problem is that getAttribute returns null all the time, although data-emo exists. is there anything i forgot or did wrong?

user14773854
  • 303
  • 4
  • 10
Laura B
  • 1
  • 1
  • You are clicking on the `img` element, not the element with eh `data-emo` attribute. – Quentin Apr 19 '22 at 15:50
  • 1
    Aside from selecting the right element, you should probably use [dataset](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset) rather than getAttribute. – Quentin Apr 19 '22 at 15:51
  • When I run your code and click the buttons, I get "sad" "happy" in console (that's because I clicked on the button and not the images). You could try e.currentTarget.getAttribute(...) instead of e.target. – James Apr 19 '22 at 15:51
  • @James That is because you don't have the images, and thus, you don't click those. – connexo Apr 19 '22 at 15:52
  • thank you, i changed it to currentTarget and now its working :) – Laura B Apr 19 '22 at 15:55
  • Better to use `const emotion = button.querySelector('img').dataset.emo;`. – connexo Apr 19 '22 at 15:56

0 Answers0