Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding custom attributes

In a rather complex HTML5 webapp that I am creating I find that it is handy to add a few custom attributes to some document elements. With jQuery I find that I can retrieve such attributes without any issues - in Chrome, Safari and Firefox thus far and, I hope, also on the Android/iPhone mobile browsers.

Question - is such usage, injecting custom attributes, ok or will I be breaking something down the line. To get things into context I am using jQuery Mobile, with jQuery and a few jQuery plugins.

On a related note I assume it is possible to retrieve all elements with a specified attribute with jQuery?

like image 436
DroidOS Avatar asked Dec 16 '22 21:12

DroidOS


2 Answers

Instead of using custom attributes, I would recommend using data attributes , which you can read about on the HTML5 Doctor Website.

Essentially, you can give elements custom attributes that are prefixed by data-, and you can read / set these with jQuery. Here's an example:

HTML5 snippet:

<p id="porky" data-food="bacon">Porky was a tasty little piggy</p>

jQuery snippet:

alert( $('#porky').data('food') ); // Alerts "bacon"
$('#porky').data('food', 'roast');
alert( $('#porky').data('food') ); // Alerts "roast"

Using the data-attributes will make for a valid, future-proof app.

like image 102
Andrew Avatar answered Jan 08 '23 22:01

Andrew


You can use data- attributes:

<div data-someattr="1" data-someotherattr="'1'" data-obj="{prop:'val1'}" ....

The retrieve those by jQuery.data():

$('div').data('someattr')           //1      Number
$('div').data('someotherattr')      //'1'    String
$('div').data('obj').prop          //'val1' String
like image 40
Engineer Avatar answered Jan 08 '23 20:01

Engineer