LuisBento
LuisBento

Reputation: 716

Difference between .getAttribute and dataset in JS

I have been using .getAttribute and today found out about .dataset, so i was wondering what the differences are and when should each be used.

So here is an example. Let's say we have a paragraph:

<p class="test" data-something="this is a test">some text</p>

if we use .getAttribute

let testText = document.querySelector('.test');
let testGetAttribute = testText.getAttribute('data-something');
console.log(testGetAttribute);

we get as output "this is a test".

if we use .dataset

let testText = document.querySelector('.test');
let testDataset = testText.dataset.something;
console.log(testDataset);

we also get "this is a test".

So, is there a difference between this two approaches? Are there some benefits in using one over the other?

Thank you!

Upvotes: 13

Views: 7954

Answers (2)

Mahdi_AK
Mahdi_AK

Reputation: 7

When you want to get data-something in JS both work or when the "data-something" is added in JS with dataset.something and want to get it.

But performance getAttribute() is better than dataset (test performance reference)

getAttribute x 123,293 ops/sec ±0.69% (64 runs sampled)

dataset x 781 ops/sec ±1.07% (61 runs sampled)

Upvotes: -1

Xavier Chia
Xavier Chia

Reputation: 257

I'm only replying this because I faced a difference between the two methods that actually affected the functioning of my application.

I did getAttribute('data-id') and dataset.id to collect a todo item id.

For getAttribute, if I ran through the debugger line by line, it worked fine. If I didn't, all sorts of wonky things would happen. For dataset.id it worked fine either way.

If you're curious about it, you can check lines 201 and 202 in my code: https://glitch.com/~wnc-reading-exercise-3 Comment out line 201 and uncomment line 201.

When running the app, try toggling complete on a todo item and see what happens to the DOM. If you go around toggling a few at a go you'll see some strange values show up.

Upvotes: 1

Related Questions