patch feedback requested: html5 data-* attrs transcend into the $.fn.data() API

patch feedback requested: html5 data-* attrs transcend into the $.fn.data() API

In the HTML5 spec, data-* attributes have been added to associate data to elements:


In jQuery, the data() method allows developers to associate data to elements and retrieve it.


And now... "with your powers combined..."


  1. <div data-patchlocation="github" data-awesome="true" data-testcount="28" />


  1. $( div ).data( 'patchlocation' // "github" 
    $( div ).data( 'awesome' // true
    $( div ).data( 'testcount' // 28




Proper JSON is supported, too:
  1. <div data-details='{"authors": ["paul irish","andrée hansson"], "prop": "html5"}' data-cacherules="everythingaroundme"/


  1. var details  $( div ).data( 'details' );
    details.authors[ 1 ] // "andrée hansson"

    // also, internal data cache preferred over DOM
    $( div ).data( 'cacherules' , 'DOLLA DOLLA' );
    $( div ).data( 'cacherules' // "DOLLA DOLLA"








This feature to data() is also proposed as a replacement to the metadata plugin .


The patch in three acts:



Worth noting:
  • The elem.dataset API (from HTML5), currently unimplemented anywhere, camelcases based on hyphens and such. This data() api does not.
  • The spec says " Authors of libraries that are reused by many authors are encouraged to include their name in the attribute names, to reduce the risk of clashes.  For example, a library called "DoQuery" could use attribute names like  data-doquery-range , and a library called "jJo" could use attributes names like  data-jjo-range ."  Requiring authors to prefix all data attr's with 'jquery-' is bit much to me, so this doesn't enforce such a thing.
  • Because JSON requires double quotes around keys, they must either be escaped or single quotes should be used for the data-* attribute value.


I've had various iterations of this for quite a while and think this is the strongest, but I'm eager to hear everyone's feedback. (Andrée Hansson (peol) worked with me on this patch; thank you sir.)