Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for data association with HTMLElement objects?

I came across 3 ways to store any data with HTMLElement object.

Can someone please suggest the best practice to associate any data with element object?

I prefer number 3 because it doesn't set any HTML attribute as in the case of 1 and 2. It's just like setting and getting any property on the object.

  1. Use setAttribute('nonStandardDataProperty')
  2. Use dataset property of HTMLElement object for example dataset.x for data-xattribute
  3. HTMLElement is object, so define any property and it will serve as data storage for that element
like image 926
P K Avatar asked Apr 02 '13 13:04

P K


2 Answers

Option #2 seems to me to be the most "standards-compliant", if that's what you're looking for; plus, it allows you to set those attributes from within the HTML while still maintaining valid markup. It's generally my preference, but it's really whatever works best for you in your situation: if it works, go with it.

like image 101
Adrian Avatar answered Oct 11 '22 13:10

Adrian


I would use option #1 because it's the most portable.

However I would use HTML5's data- prefix for those custom attributes for compatibility with jQuery's .data() method.

like image 30
Alnitak Avatar answered Oct 11 '22 14:10

Alnitak