jQuery append()-返回附加的元素

我使用jQuery.append()来动态添加一些元素。有没有办法获得这些新插入元素的jQuery集合或数组?

所以我想这样做:

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

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.

var newElementsAppended = $(newHtml).appendTo("#myDiv");
newElementsAppended.effects("highlight", {}, 2000);
// 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);

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]"

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.