views:

207

answers:

1

I have a documentFragment with several child nodes containing some .data() added like so:


myDocumentFragment = document.createDocumentFragment();
for(...) {
  myDocumentFragment.appendChild(
    $('<a></a>').addClass('button')
      .attr('href', 'javascript:void(0)')
      .html('click me')
      .data('rowData', { 'id': 103, 'test': 'testy' })
      .get(0)
  );
}

When I try to append the documentFragment to a div on the page:

$('#div').append( myDocumentFragment );

I can access the data just fine:

alert( $('#div a:first').data('rowData').id ); // alerts '103'

But if I clone the node with cloneNode(true), I can't access the node's data. :(

$('#div').append( myDocumentFragment.cloneNode(true) );
...
alert( $('#div a:first').data('rowData').id ); // alerts undefined

Has anyone else done this or know of a workaround? I guess I could store the row's data in jQuery.data('#some_random_parent_div', 'rows', [array of ids]), but that kinda defeats the purpose of making the data immediately/easily available to each row.

I've also read that jQuery uses documentFragments, but I'm not sure exactly how, or in what methods. Does anyone have any more details there?

Thanks!

Edit re: .clone(true)


$(globalObj).data('fragment', { frag: $(mydocumentFragment).clone(true) });

$(myDocumentFragment).clone(true).appendTo('#div');

alert( $('#div a:first').data('rowData').id ); // undefined
A: 

You're creating a jQuery object when you do $('a'), but you're leaving it behind when you use get(0) and use appendChild to append it to your fragment. So if you use the native .cloneNode(true) on your fragment, jQuery is not aware of it, and therefore is not managing the data for you.

As long as you're using jQuery for most of what you're doing, I'd say ditch the documentFragment, and just stuff your a elements into a jQuery object, and clone() that.

I don't think you're gaining anything by using a fragment in this case.

patrick dw
thanks that's probably what i'm going to end up doing, i'm about to give up :)
taber
Yeah, if you're going to use `.data()`, you should probably plan on sticking with jQuery. If you can get by without it, you'll have an easier time going native.
patrick dw
true. alright screw it. :) thanks anyway for the help, i appreciate it. on a side note, i tried $list = $({}); and got an error saying that doc.createDocumentFragment was not a function in jquery-1.4.2.js - so if i change that to $('<div></div>') it looks like they are using documentFragments there anyhow! cool. thanks again.
taber