jQuery append() - return appended elements

Jquery

Jquery Problem Overview


I'm using jQuery.append() to add some elements dynamically. Is there any way to get a jQuery collection or array of these newly inserted elements?

So I want to do this:

$("#myDiv").append(newHtml);
var newElementsAppended = // answer to the question I'm asking
newElementsAppended.effects("highlight", {}, 2000);

Jquery Solutions


Solution 1 - Jquery

There's a simpler way to do this:

$(newHtml).appendTo('#myDiv').effects(...);

This turns things around by first creating newHtml with jQuery(html [, ownerDocument ]), and then using appendTo(target) (note the "To" bit) to add that it to the end of #mydiv.

Because you now start with $(newHtml) the end result of appendTo('#myDiv') is that new bit of html, and the .effects(...) call will be on that new bit of html too.

Solution 2 - Jquery

// wrap it in jQuery, now it's a collection
var $elements = $(someHTML);

// append to the DOM
$("#myDiv").append($elements);

// do stuff, using the initial reference
$elements.effects("highlight", {}, 2000);

Solution 3 - Jquery

var newElementsAppended = $(newHtml).appendTo("#myDiv");
newElementsAppended.effects("highlight", {}, 2000);

Solution 4 - Jquery

A little reminder, when elements are added dynamically, functions like append(), appendTo(), prepend() or prependTo() return a jQuery object, not the HTML DOM element.

DEMO

var container=$("div.container").get(0),
    htmlA="<div class=children>A</div>",
    htmlB="<div class=children>B</div>";

// jQuery object
alert( $(container).append(htmlA) ); // outputs "[object Object]"

// HTML DOM element
alert( $(container).append(htmlB).get(0) ); // outputs "[object HTMLDivElement]"

Solution 5 - Jquery

I think you could do something like this:

var $child = $("#parentId").append("<div></div>").children("div:last-child");

The parent #parentId is returned from the append, so add a jquery children query to it to get the last div child inserted.

$child is then the jquery wrapped child div that was added.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpsychotikView Question on Stackoverflow
Solution 1 - JquerySLaksView Answer on Stackoverflow
Solution 2 - Jquerykarim79View Answer on Stackoverflow
Solution 3 - JqueryThiago BelemView Answer on Stackoverflow
Solution 4 - JqueryAgelessEssenceView Answer on Stackoverflow
Solution 5 - JqueryaffView Answer on Stackoverflow