1

I can't understand why e.target.name is showing undefined even though e.target returns the node. How would I simply change the text using the event object?

function changeText(e) {
  console.log(e.target, e.target.name);
  
  switch (e.target.name) {
    case 'fooBar':
      e.target.innerHTML = 'bar';
      break;
  }
}
<div>
  <p name="fooBar" onclick="changeText(event)">foo</p>
</div>
Andreas
  • 21,535
  • 7
  • 47
  • 56
algojedi
  • 57
  • 1
  • 4
  • `HTMLParagraphElement` does not have a `name` property. Also, the `name` attribute is **invalid** for `

    ` elements. Use `data-name="fooBar"` instead and access it using `event.target.dataset.name`.

    – connexo Jan 23 '20 at 13:25

1 Answers1

0
function changeText(e) {
    console.log(e.target.getAttribute('name'));
    switch (e.target.getAttribute('name')) {
    case 'fooBar':
        e.target.innerHTML = 'bar';
        break;
    }
}

e.target is a html node so you have to use DOM api to get attributes

Narek Gevorgyan
  • 113
  • 1
  • 12
  • Thanks for this solution. I'm still a little confused though why e.target.someAttribute seems to work fine in my webpage when it's attached to an img tag, but not when it's from a p tag. Very strange – algojedi Jan 23 '20 at 15:40
  • depends what attribute you're talking about, for example `Id` and `className` would work , but `name` wouldn't. think about `e.target` as a js class which has public `id` and `className` properties, but `name` for example is private, and to get it you should call instance method. – Narek Gevorgyan Jan 24 '20 at 10:24