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;
1
  • 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. Commented May 17, 2020 at 11:34

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, not sure why I was blanking on using [] but that makes so much sense!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.