9

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!

LuisBento
  • 678
  • 9
  • 16
  • 2
    In HTML, you should only add attributes that are specified as belonging to the particular HTML element. If you create your own named attributes, you risk a name clash with a current or future attribute names. So *data-\** attributes were created so you can use it as a prefix for any attribute you wish to add. The rest you can get from [*MDN*](https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes). The use of *dataset* is just a convenient getter, rather than using `element.getAttribute(data-whatever)`. – RobG Sep 26 '18 at 09:37
  • 3
    `dataset` is more recent, works in current browsers and makes nicer code to read, but if you're handling large numbers of `data` attributes, it's slower that `getAttribute`, although that speed difference is negligible for smaller cases, where `dataset` is fine. See https://jsperf.com/getattribute-vs-dataset – Dave Everitt Mar 22 '19 at 13:37
  • `dataset` [compatibility](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset#browser_compatibility) is really good, so performance aside it will hardly crash anywhere – Adrià Jan 17 '22 at 17:14

1 Answers1

2

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.

Xavier Chia
  • 203
  • 3
  • 5