Wednesday 23 May 2012

CUSTOM ATTRIBUTES FOR HTML ELEMENTS

Custom attributes on HTML elements have been quite handy for storing custom values. Though they were not standardized in previous HTML specifications, browsers allowed their usage. In the HTML5 specification, they have been standardized, making them a nice little tool in the developer's box.

HTML5 IMPLEMENTATION

For usage the custom attributes names must be prefixed by "data-", therefore making a valid custom attribute name be "data-foo". The custom attribute values implementation remain as before.
An example


ACCESS
There are two methods to retrieve and set the values of the custom attributes are as follows:-

GetAtrribute & SetAtrribute
 The previously known method of using the getAttribute and setAttribute methods for getting and setting the custom attributes.
Here is an example:


DATASET
The dataset method is a new method implemented in the HTML5 specification. The code snippet below shows and example of its usage.

Note: This method has not been implemented in any browser yet, so stick to the getAttribute/ setAttribute option. The other benefit is backward compatibility for older browsers.


In this method only the string prefixed by "data-" is used as the object of the dataset property to access the specific custom attribute.

Note: This method has not been implemented in any browser yet, so stick to the getAttribute/ setAttribute option. The other benefit is backward compatibility for older browsers.

For more reading:
http://html5doctor.com/html5-custom-data-attributes/
http://ejohn.org/blog/html-5-data-attributes/

No comments:

Post a Comment