0

I am getting <td value="1414">Nishant</td> by event.target. I want 1414 and as I try to get value by using event.target.value I am getting undefined. How can I get that value?

Nishant Khandelwal
  • 199
  • 1
  • 5
  • 13
  • 3
    That is invalid HTML. `` elements do not have a value. But you can still get it by using `event.target.getAttribute('value')` – blex Aug 19 '17 at 20:24
  • 1
    `value` isn't valid attribute of `td` element. You can try `data-value` attribute and `event.target.getAttribute['data-value']` – Alex Kudryashev Aug 19 '17 at 20:26

2 Answers2

1

td elements don't have value. What you are looking for is to get the value of the attribute value of that element.

You can do this using the getAttribute function:

console.log(document.getElementById('a').getAttribute('value'));
<table>
  <tr>
    <td id="a" value="123">a</td>
  </tr>
</table>
Dekel
  • 60,707
  • 10
  • 101
  • 129
1

You should use data-* in order to "save" custom data on DOM node. And then access it via domNode.dataset.* as a camelCase.

document.querySelector("table").addEventListener("click",function(e) {
  console.log(e.target.dataset.value);
})  
<table>
  <tr>
    <td data-value="123">a</td>
  </tr>
</table>

for very old browsers you can use e.target.getAttribute("data-value")

mplungjan
  • 169,008
  • 28
  • 173
  • 236
felixmosh
  • 32,615
  • 9
  • 69
  • 88