jQuery appending an array of elements

后端 未结 9 685
星月不相逢
星月不相逢 2020-12-13 23:34

For the purpose of this question lets say we need to append() 1000 objects to the body element.

You could go about it like this:

         


        
相关标签:
9条回答
  • 2020-12-13 23:53

    Sometimes, jQuery isn't the best solution. If you have a lot of elements to append to the DOM, documentFragment is a viable solution:

    var fragment = document.createDocumentFragment();
    for(var i = 0; i < 1000; i++) {
        fragment.appendChild(document.createElement('div'));
    }
    document.getElementsByTagName('body')[0].appendChild(fragment);
    
    0 讨论(0)
  • 2020-12-13 23:53

    I would use native Javascript, normally much faster:

    var el = document.getElementById('the_container_id');
    var aux;
    for(x = 0; x < 1000; x++) {
        aux = document.createElement('div');
        aux.innerHTML = x;
        el.appendChild(aux);
    }
    

    EDIT:

    There you go a jsfiddle with different options implemented. The @jackwander's solution is, clearly, the most effective one.

    0 讨论(0)
  • 2020-12-13 23:59

    I know, the question is old, but maybe it helps others.

    Or simple use ECMA6 spread operator:

    $('body').append(...elements);
    
    0 讨论(0)
  • 2020-12-14 00:09

    A slight change to your second approach:

    var elements = [],
    newDiv;
    for (x = 0; x < 1000; x++) {
        newDiv = $('<div/>').text(x);
        elements.push(newDiv);
    }
    $('body').append(elements);
    

    $.append() certainly can append an array: http://api.jquery.com/append/

    .append(content) | content: One or more additional DOM elements, arrays of elements, HTML strings, or jQuery objects to insert at the end of each element in the set of matched elements.

    0 讨论(0)
  • 2020-12-14 00:10

    If you're going for raw performance then I would suggest pure JS, though some would argue that your development performance is more important than your site's/program performance. Check this link for benchmarks and a showcase of different DOM insertion techniques.

    edit:

    As a curiosity, documentFragment proves to be one of the slowest methods.

    0 讨论(0)
  • 2020-12-14 00:14

    Since $.fn.append takes a variable number of elements we can use apply to pass the array as arguments to it:

    el.append.apply(el, myArray);
    

    This works if you have an array of jQuery objects. According to the spec though you can append an array of elements if you have the DOM elements. If you have an array of html strings you can just .join('') them and append them all at once.

    0 讨论(0)
提交回复
热议问题