0

I need to store data (a string) on a certain HTML node.

This can be done via the dataset object

document.body.dataset.foo = 'bar';

Given the nature of JS however, node instances are also (just) objects, and thus you can also simply define a new property implicitly on the fly like so:

document.body.bar = 'foo';

Both methods fulfill the requirement of storing and then retrieving data of simple types.

I'm aware of the following differences:

  • dataset writes the the information as attribute on the node (data-{key}="{value}")
  • by using the subobject (dataset) you are less likely to overwrite an existing property

In my case, I would prefer not to have the information written as data-attribute, so I lean towards the property approach. Most sources on the internet however want you to use the dataset method.

Am I missing something here? Are there any other particularities to consider?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
LukasKroess
  • 125
  • 2
  • 13
  • Am I correct in assuming you want to prevent exposure of the data, thus you don't want to use the custom attributes? – VLAZ Jan 09 '23 at 13:10
  • Though [this post](https://stackoverflow.com/q/6223449/1169519) talks about JS prototype object, the same can be applied to DOM elements too. In the past, there was a JS library called prototype.js. It was based on setting custom properties of the element's prototype, but the disadvantages bit too hard, and the project was later buried. – Teemu Jan 09 '23 at 13:13
  • @VLAZ I don't want it to clutter up the inspector tree. It is not about security – LukasKroess Jan 09 '23 at 13:24
  • @Teemu I actually used prototype.js a lot before my company switched to jQuery. Now, however I'm sticking with vanilla ES5/6 and imho besides the name, the library has very little to do with the concept of prototyping. Also in this szenario I'm not interested in prototyping, since the data is not static. OOOORRRRR I'm using the term prototyping wrong, which would invalidate both points of this comment. To me, prototyping means adding members (fields or methods) to a class, so that they are available to all future instances which would not benefit my problem – LukasKroess Jan 09 '23 at 13:30
  • Prototype.js was based on prototype patching. Your prototype explanation is correct. Custom element attributes are just from the same root, see ex. https://stackoverflow.com/a/71990624/1169519 . The most important reason to not to use custom attributes is, they're not standard compatible, every validation engine will fail, and also possibly some environments fail. We've had [Map object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) for years, after it was introduced, I haven't needed even `data-*` attributes. – Teemu Jan 09 '23 at 13:50

0 Answers0