views:

35

answers:

2

Hello, 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 smarter move here. I'm used to do it like that from Prototype..

+1  A: 

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.

Sarfraz
Why `.appendTo($("body"))`, why not just `.appendTo("body")`?
Andy E
Novice users might benefit from your example if you add a version with everything broken up. e.g. `$div = $("div"); $div.html(".."); $("body").append($div);` what you present is what we use (+1), but it'd be confusing to someone new to jquery
Michael Haren
doesn't $('div').appendTo("body") adds all the defined div elements in the current page back to the body?
Quamis
got it, it should have been $("<div>text</div>").appendTo.... thx
Quamis
A: 

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