开发者

How to get reference to jQuery selector for content just added via manipulation method?

开发者 https://www.devze.com 2022-12-18 23:59 出处:网络
If content is added to the开发者_开发问答 DOM using, e.g., $(\"ul\").append(\"<li>test</li>\");

If content is added to the开发者_开发问答 DOM using, e.g.,

$("ul").append("<li>test</li>");

how does one get a reference the content just added w/o having to select the newly added content?

Assigning the return value from the append() method is the jQuery object.

var newContent=$("ul").append("<li>test</li>");

One could do

var newContent=$("ul li:last");

but is there a way to get it more directly?

Thanks


Use .appendTo():

Insert every element in the set of matched elements to the end of the target...

The .append() and .appendTo() methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With .append(), the selector expression preceding the method is the container into which the content is inserted. With .appendTo(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container...


You can create it in its own line ala:

var newLi = $('<li>test</li>');
$('ul').append(newLi);

//Continue using newLi and it will affect the appended element
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号