Return inserted item

I am new to jquery. I am trying to insert an element into the DOM and get that element back in my script.

Example:


    var elem = $("body").append("");
    $(elem).show();

      

but it seems like .append is returning the entire jQuery object. Should I use an id for the inserted element and always refer to it? I really hope there is a smarter move here. I'm used to doing this with Prototype ..

+2


a source to share


2 answers


Let's say you want to create div

:

var elem = $("div").appendTo("body").html('some html for the div').hide();
$(elem).show();

      



The above code creates div

, sets the html for it with html()

and hides it first because you want to show it later.

Note: Please note that I have written different methods / functions on the same line, this is called chaining in JQuery and yes very useful.

+1


a source


The append()

method $()

doesn't do anything that the method couldn't do when it came to creating the element. The only difference is what append()

adds it to the DOM.

In this way,

$("body").append(XXXXX);

      



does not differ from

var elem = $(XXXXX);
$("body").append(elem);

      

0


a source







All Articles