Access HTML dataset

1k Views Asked by At

I am trying to access a dataset in my HTML. Normally if it was:

<td data-mmyyyy="23"></td>

You could access it with

tdObj.dataset.mmyyyy

but for some reason that is not working for me here.

var mmyyyy = tds[i].dataset.mmyyyy.split('/');

I stopped it on the debugger and output the following from the console:

tds // (ME)
  [(enumerated td nodes)] // (CONSOLE)
tds[i] // (ME)
  <td> // (CONSOLE)
    <a href="#" data-mmyyyy="3/2015">22</a>
  </td>
tds[i].dataset // (ME)
  DOMStringMap {}  // (CONSOLE)
tds[i].dataset.mmyyyy // (ME)
  undefined  // (CONSOLE)

Can anyone tell me how to approach this differently to access that data attribute? Thanks.

2

There are 2 best solutions below

0
On BEST ANSWER

If you look better at the console, you'll see that it logs this:

<td>
    <a href="#" data-mmyyyy="3/2015">22</a>
</td>

So, according to the data logged by the console, the dataset you're trying to access is not on your <td> element, but on its <a> child.

To access it you can do this:

tds[i].children[0].dataset.mmyyyy

Or, better, with querySelector:

tds[i].querySelector("a").dataset.mmyyy
0
On

My mistake! The dataset is on the tag within the tag. So the correct accessor will be

tds[i].children[0].dataset.mmyyyy