return the inserted element
i'm pretty new to jquery. I'm trying to insert an element to the DOM, and get that element back in my script.
Ex:
var elem = $("body").append("");
$(elem).show();
but it seems that .append returns the whole jQuery object.. am i supposed to use an ID for the inserted element and always reference it by it?? i really hope that there is a 开发者_JAVA技巧smarter move here. I'm used to do it like that from Prototype..
Let's suppose you want to create a div
:
var elem = $("div").appendTo("body").html('some html for the div').hide();
$(elem).show();
The above code create the div
, sets some html for it using html()
and hides it initially on because later you want to show it.
Note: Note that I have written different methods/functions on the same line, this is known as chaining in JQuery and yes very useful.
The append()
method does nothing that the $()
method couldn't do when it comes to element creation. The only difference is that append()
adds it to the DOM.
Thus
$("body").append(XXXXX);
is no different to
var elem = $(XXXXX);
$("body").append(elem);
精彩评论