0

I have been using:

var data = element.getAttribute('data-name');

But it seems easier to use 'dataset'

var data = element.dataset.name

But my question is: Is there anyway I can use element.dataset with a var? For example I can't get this to work:

var dataName = 'test';

var data = element.dataset.dataName;
  • Presumably `element` is a DOM element, and `element.dataset` gives its `data-*` attributes. I'm not sure why you would think that it would give access to arbitrary variables. – Robin Zigmond May 17 '20 at 11:34

1 Answers1

1

Consider what the code you wrote actually does.

var data = element.dataset.name is the code which works and you're familiar with – it looks for a property called name inside element.dataset. In this case, name is not an identifier which refers to a variable.

In exactly the same way, the code element.dataset.dataName looks for a property dataName inside element.dataset. dataName is not seen as an identifier.

What you want to do is look for a property called test, the content of your variable dataName.

To do that, you need to use bracket notation:

var dataName = 'test';

var data = element.dataset[dataName];

Here is a working code snippet which demonstrates this method:

var element = document.getElementsByTagName('div')[0];

var dataName = 'test';
var data = element.dataset[dataName];

console.log(data);
<div data-test="success"></div>

You could also look into variable variables, although many people would recommend against using them in javascript when it is not necessary.

Run_Script
  • 2,487
  • 2
  • 15
  • 30
  • Thanks, not sure why I was blanking on using [] but that makes so much sense! –  May 17 '20 at 22:23