简体   繁体   中英

jQuery append to jQuery variable instead of DOM element

Is it possible to append to jQuery variable?

someting like this $($tnail).appendTo($collection);

I need to optimize costly DOM modifications and want to do it all at once.

something like this:

    var $collection;

 $.each(items, function (i, item) {

        var $tnail = $("<div></div>");

        $($tnail).appendTo($collection);

    });

    $($collection).appendTo("#Container");

Yes! You just need to make sure $collection is a jQuery object:

var $collection = $('<x/>');

$.each(items, function (i, item) {

    var $tnail = $("<div></div>");

    $tnail.appendTo($collection);

});

$($collection.html()).appendTo("#Container");

You've also got 2 bits where you wrap a jQuery object in a new jQuery call: $tnail is already a jQuery wrapped div, so it already has the appendTo method. Even more performance benefits!

EDIT: As Kevin points out, you can't append to an empty jQuery object. Internally, jQuery uses empty document fragments, but it doesn't expose this through it's API. So I've change my solution to create a dummy element, and then only append its contents to #Container .

You don't actually want to append the elements to $collection, you want to add them to it.

var $collection = $(); // must be a jquery object
$.each(items, function (i, item) {

    var $tnail = $("<div></div>");

    // add to collection
    $collection.add($tnail);

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM