1

I prefer using attributes like lang, dir, id, class and others to store useful data for some javascript functions that reference these objects - I do this to avoid using an array that may have to be updated after every action or change. The problem is that this is a bad practice and I cannot always use the attributes I want, because they're already in use or not available on some tag types. Is there a better way?

Note that I dont like using multiple values split with a separator as this is slow when dealing with massive amounts of objects.

hichris123
  • 10,145
  • 15
  • 56
  • 70
Johnny Darvall
  • 587
  • 2
  • 7
  • 17

2 Answers2

7

HTML5 data-* attributes were designed especially for this. From the spec:

Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.

You can use them like this:

<div data-random="12345" data-name="James"></div>

They are valid on all elements, and every element can have any number of them.

They can be accessed through the dataset property, which every element should have. If you use jQuery, you can use the data method to help resolve issues with older browsers (and IE). If not, you may have to feature-detect the dataset property and fall back to getAttribute where dataset is not supported.

James Allardice
  • 164,175
  • 21
  • 332
  • 312
0

Since you tagged both jQuery and HTML5, I think this is precisely what you are looking for, in a elegant and standardized way, without breaking validation.

HTML5 data-* Attributes

ericosg
  • 4,926
  • 4
  • 37
  • 59