0

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");
2
  • In your code $collection should be a jQuery object. Commented Mar 27, 2013 at 18:02
  • If you really want to optimize, you'll do this ! Commented Mar 27, 2013 at 18:18

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm not sure what the result of this code will be, $collection doesn't contain any elements for $tnail to be appended to. I'd expect it to do nothing
1

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);

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.