I need to append multiple nodes to a container. Rather than doing a slow DOM append inside each iteration, I want to queue up the nodes in a document fragment (open to other ideas) and append them all at one time. Here is my code:
var fragment = document.createDocumentFragment();
$.each( poFailureInfoMultiple, function(i,e){
fragment.appendChild(
$('<button/>', {
'class': 'el-contents-center multiple-record'
})
);
});
$('#some-container').html( fragment );
My problem is I am getting an error message stating:
Could not convert JavaScript argument arg 0 [nsIDOMDocumentFragment.appendChild]
So how can I append multiple element nodes to my DOM at once? I don't HAVE to use the fragment method (I just found it and it seemed viable).
Note: I DO NOT WANT TO USE HTML SYNTAX FOR THE APPEND
i.e. $('#some-container').append('<button class="myclass"></button>');
var elemsToAppend=$()
$.each( poFailureInfoMultiple, function(i,e){
elemsToAppend = elemsToAppend.add(
$('<button/>', {
'class': 'el-contents-center multiple-record'
})
)
});
$('#some-container').append(elemsToAppend)
The add method on a jQuery object doesn't alter the object itself but returns a new object, which is why you need elemsToAppend = elemsToAppend.add(...)
. I honestly cant say how fast this method is though. I actually think the html way is faster though.
You are mixing document fragments with jQuery, passing the wrong arguments. appendChild
doesn't take a jQuery
object and $.html
does not take a DocumentFragment
That's what your error is telling you.
Example http://jsfiddle.net/YNLzg/
var fragment = document.createDocumentFragment();
$.each( [1,2,3], function(i,e){
fragment.appendChild(
$('<button/>', {
'class': 'el-contents-center multiple-record'
})[0] // passing the HTMLElement to appendChild, not a jQuery object
);
});
// Can't call $.html() and pass it a fragment, call appendChild.
document.getElementById('ct').appendChild(fragment);
$('#some-container').append(fragment.childNodes);
will do the job. For a fun example, run this in the console:
var f = document.createDocumentFragment();
var div = document.createElement('div');
div.innerHTML = "<h1>This heading was not here before :)</h1>";
f.appendChild(div);
$('body').append(f.childNodes);
The heading will appear at the bottom of the page. (Tested in Chrome, FF7, and IE8)
UPDATE: To clarify how this applies to the code in your OP:
var fragment = document.createDocumentFragment();
$.each(poFailureInfoMultiple, function (i, e) {
var btn = document.createElement('button');
btn.cssClass = 'el-contents-center multiple-record';
fragment.appendChild(btn);
});
$('#some-container').append(fragment.childNodes);
If you would choose html syntax for append (demo):
$(selector)
.append(arrayOfContents.map(function(s){return "<span>"+s+"</span>";}).join(''));
来源:https://stackoverflow.com/questions/11037403/jquery-how-to-append-multiple-nodes-to-container