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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With