Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

concatenating jQuery objects

Below is the prototype of what I am 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 document DOM only once when inserting data. I would usually go HTML string approach (simply concatenating the same structure using a string), but I am interested whether anything similar to this might work as well.

like image 346
Gajus Avatar asked Sep 17 '26 04:09

Gajus


1 Answers

You could create an empty DOM element and .append() to that

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/

like image 80
xec Avatar answered Sep 19 '26 16:09

xec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!