Set data on an element while it is just HTML

Set data on an element while it is just HTML

I think it would be very useful to allow setting of data on an element without a reference to the actual element.  This is for performance reasons.  The following is a longer explanation.

I use data a lot.  I typically use it in the following (and I believe, extremely common) pattern:

  1. Get data from a service
  2. Convert that data to html
  3. Insert HTML into the page
  4. Iterate through html to add service data on the elements
A good example of this would be a tree.  When someone expands the tree, I need to get the data from the element they clicked on.

The problem is if you have 1000s of elements, doing a query, and then iterating over every element is rather expensive.  This could be much faster if jQuery allowed me to set an attribute value in HTML that could be later read by $.data.


I'd like to do something like:

  1. var htmls =[]:
  2. $.each(files, function(file){
  3.    htmls.push('<div ',$.dataAttr("file",files),">",file.name,"</div>");  
  4. })
  5. $('#folderWithManyFiles').html(htmls.join(''))

$.dataAttr is my own helper function that:

  1. Increments uuid and creates a new object at jQuery.cache[uuid].
  2. Sets the data passed in $.dataAttr in the new object at jQuery.cache[uuid]
  3. Returns jQuery23452141412412='5' (where jQuery23452141412412 is jQuery.expando and 5 is uuid).

For $.dataAttr to even be possible, 2 changes would have to be made:

1.  uuid would be available on jQuery.  Maybe jQuery._uuid to warn people not to abuse it.
2.  data would check for a jQuery.expando attribute.  If present, it would use its value with jQuery.cache to get data for that element.

Just to be clear: I am not proposing dataAttr.

I want to be able to make functionality like this possible so data can work with the pattern at a much larger scale.  On my workstation, in IE6 vmware, it takes 213 ms to query on the dom, iterate through, and set data on 1000 elements.  This become nothing if I could set data ahead of time.

If this sounds good, I'll submit a pull request hopefully by tomorrow.