jQuery - how to append multiple nodes to container

余生颓废 提交于 2019-12-06 12:58:45
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(''));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!