Recommendations for combining data with HTMLElement objects?

I came across three ways to store any data using the HTMLElement object.

Can anyone suggest a best practice for associating any data with an element of an element?

I prefer number 3 because it does not set any HTML attributes, as is the case with 1 and 2. This is exactly the same as setting and getting any properties of the object.

  • Use setAttribute ('nonStandardDataProperty')
  • Use the dataset property of an HTMLElement object, for example, dataset.x for XAttribute data
  • HTMLElement is an object, so define any property and it will serve as the data store for this element.
+7
source share
6 answers

Option number 2 seems to me the most "standards compliant" if that is what you are looking for; plus, it allows you to set these attributes from HTML, while maintaining the correct markup. This is generally my preference, but it really is what works best for you in your situation: if it works, go with it.

+2
source

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

However, I would use the HTML5 data- prefix for these custom attributes for compatibility with the jQuery .data() method.

+1
source

The third option is to store data in the DOM, which might not be a bad idea if the data is not huge. If so, then storing and retrieving data may affect application performance.

0
source

I think the best way is to use HTML5 data - * Attributes and jQuery.data (). It will probably have a better way to store data in embedded HTML elements and update them to the latest technologies, so you can lean back and be productive

<div id="myDiv" data-my-var="my-var-value"></div>

can be used in JavaScript: (jQuery required)

console.log( $( '#myDiv' ).data( 'my-var' ) )

Edit: and set this as

$( '#myDiv' ).data( 'my-var', 'my-new-var-value' );

which will also update the data- * attribute in this case

0
source

Option 4: save the identifier on the DOMNode, which you can use to view things on a separate map (yes, this is the way jQuery does), in addition to importing all data- * attributes during init, of course).

The C # 3 transition is fine if you don't mind your property names. # 2 should only allow Integer and String values, # 1 may have the same problem.

I would go C # 4, simply because I don’t like the chances of a new specification and the assertion of the property name that I used for my own data ...

0
source

Twitter Bootstrap uses option 1.

Take a look at the Twitter Bootstrap file , you will see many uses for storing data in custom property html elements.

Example

 <ul class="dropdown-menu pull-right" role="menu" aria-labelledby="dLabel"> ... </ul> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> 
-one
source

All Articles