3

HTML snippet:

<input title="List" data-id="1698481">

In IE 11 console, I've been trying various commands, and everything without a hyphen comes back correctly until I hit "data-id."

document.getElementsByTagName("input")[0].title
"List"
document.getElementsByTagName("input")[0].data-id
'id' is undefined

As per other threads on this subject, I tried other syntaxes (camel case, etc.), but I still can't get it to return any value

document.getElementsByTagName("input")[0].dataId
undefined
document.getElementsByTagName("input")[0].["data-id"]
Expected identifier
document.getElementsByTagName("input")[0].['data-id']
Expected identifier

Any assistance would be appreciated.

enter8
  • 41
  • 1
  • 3
  • [Access 'data-' attribute without jQuery](http://stackoverflow.com/questions/15912246/access-data-attribute-without-jquery) and [How to get the data-id attribute?](http://stackoverflow.com/questions/5309926/how-to-get-the-data-id-attribute) – Jonathan Lonowski May 20 '16 at 20:54
  • I recommend to revisit some JavaScript basics about accessing properties: https://stackoverflow.com/questions/11922383/access-process-nested-objects-arrays-or-json. (`[0].['data-id']` is simply invalid syntax) – Felix Kling May 20 '16 at 21:13

2 Answers2

4

Use .getAttribute():

document.getElementsByTagName("input")[0].getAttribute("data-id")
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
1

The data-* attributes are special:

document.getElementsByTagName("input")[0].dataset.id

data-* attributes are converted from hyphens to camelCasing, so a data-test-attribute="test" would be equivalent to:

htmlElement.dataset.testAttribute; // test

For more information, see the MDN on dataset.

jeffjenx
  • 17,041
  • 6
  • 57
  • 99