Concatenating jQuery objects

Below is a prototype of what I'm trying to do.

var entry_set   = $;

// start to loop data
for([])
{
    // create HTML element to represent that data
    $('<div></div>')
        .data([])
        .addClass([])
        .on([])
        .insertAfter(entry_set);
}

// modify DOM only once all the entries are consolidated to a single jQuery object
entry_set.appendTo('.entries');

The comments say it all. In short, the idea is to modify a DOM document only once when inserting data. I usually use the HTML approach (just concatenating the same structure using a string), but I'm wondering if something like this can work with this.

+3
source share
3 answers

You can create an empty DOM element and .append () for this

var entry_set = $("<div>"); //empty dom element

// start to loop data
var i = 4;
while(i--) {
    // create HTML element to represent that data
    var item = $('<div>', {
        text: "test " + i
    });
    entry_set.append(item);
}

// modify DOM only once all the entries are consolidated to a single jQuery object
$("body").append(entry_set.children());​

working demo at: http://jsfiddle.net/F2J6g/1/

EDIT You can also start with an empty collection and use .add ()

var entry_set = $(); //empty collection

// start to loop data
var i = 4;
while(i--) {
    // create HTML element to represent that data
    var item = $('<div>', {
        text: "test " + i
    });
    entry_set = entry_set.add(item);
}

// modify DOM only once all the entries are consolidated to a single jQuery object
$("body").append(entry_set);

http://jsfiddle.net/F2J6g/2/

+2
source

@Guy, , HTML. "wrap". :

$('.OuterDiv').wrap('<div class="abc" />');
0

Unfortunately, since these objects are not actually attached to any hierarchy, the call insertAfterdoes not really mean anything. What you need to do is put them in the containing div, maybe something like this:

var entry_set = $('<div>');

// start to loop data
for([])
{
    // create HTML element to represent that data
    $('<div></div>')
        .data([])
        .addClass([])
        .on([])
        .appendTo(entry_set);
}

// modify DOM only once all the entries are consolidated to a single jQuery object
entry_set.appendTo('.entries');

I have not tested this, but I think it should work.

0
source

All Articles