user12097954
user12097954

Reputation:

Accessing data attributes with JavaScript

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;

Upvotes: 0

Views: 1718

Answers (1)

Run_Script
Run_Script

Reputation: 2548

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.

Upvotes: 1

Related Questions