I want to use document.createDocumentFragment() to create an optimized collection of HTML elements that contain “.data” coming from jQuery (v 1.4.2), but I’m kind of stuck on how to get the data to surface from the HTML elements.
Here’s my code:
var genres_html = document.createDocumentFragment();
$(xmlData).find('genres').each(function(i, node) {
var genre = document.createElement('a');
$(genre).addClass('button')
.attr('href', 'javascript:void(0)')
.html( $(node).find('genreName:first').text() )
.data('genreData', { id: $(node).find('genreID:first').text() });
genres_html.appendChild( genre.cloneNode(true) );
});
$('#list').html(genres_html);
// error: $('#list a:first').data('genreData') is null
alert($('#list a:first').data('genreData').id);
What am I doing wrong here? I suspect it’s probably something with .cloneNode() not carrying over the data when the element is appended to the documentFragment. Sometimes there are tons of rows so I want to keep things pretty optimized, speed-wise.
Thanks!
You’re running
cloneNodeon a jQuery object. You start off with native API, then convert it to a jQuery object, then switch back.I suppose you could do:
But then I suspect you would lose your
data.EDIT:
If you want jQuery, instead of creating a fragment, try creating an empty jQuery object, then pushing each genre into it:
EDIT:
Give this a try. I’m no DOM expert, but it may work for you.
Let me know if it works.
EDIT: Changed my error with innerHTML
EDIT2: Using native innerHTML to append to
#list