Hai Truong IT
Hai Truong IT

Reputation: 4187

Can't using append and appendChild in a jQuery?

I have a sample code:

jQuery(document.body).append('<div id="wrapper-1"></div>').appendChild('<div id="wrapper-2"></div>');

How to get this result, how to ideas?

<div id="wrapper-1">
   <div id="wrapper-2"></div>
</div>

Upvotes: 0

Views: 176

Answers (7)

GiantHornet
GiantHornet

Reputation: 102

try this:

var $div1 = $("<div/>");
$div1.attr("id", "wrapper-1");

var $div2 = $("<div/>");
$div2.attr("id", "wrapper-2");

$div1.append($div2);



 <div id="wrapper-1">
    <div id="wrapper-2"></div>
  </div>

Upvotes: 0

Rusty
Rusty

Reputation: 1303

or else you can try this:

$('.body').append('<div id="wrapper-1"></div>');
$('<div id="wrapper-2"></div>').appendTo('#wrapper-1');

Upvotes: 2

Dipendra Gurung
Dipendra Gurung

Reputation: 5870

appendChild() is a javascript native function, while append() is a jquery method. So both in a chain won't work as you expect.

Try this as suggested by Maxim.

jQuery('body').append('<div id="wrapper-1"><div id="wrapper-2"></div></div>');

Upvotes: 0

Steve Wellens
Steve Wellens

Reputation: 20620

Here's a way:

jQuery(document.body).append('<div id="wrapper-1"></div>').children().append('<div id="wrapper-2"></div>');

Upvotes: 1

techfoobar
techfoobar

Reputation: 66663

append() is a jQuery method whereas appendChild() is a DOM Element method.

i.e. you need to call appendChild() on a pure DOM element. The following should work.

jQuery(document.body).append('<div id="wrapper-1"></div>')[0].appendChild('<div id="wrapper-2"></div>');

Upvotes: 0

Maxim Pechenin
Maxim Pechenin

Reputation: 344

jQuery('body').append('<div id="wrapper-1"><div id="wrapper-2"></div></div>');

Upvotes: 1

Scott Selby
Scott Selby

Reputation: 9570

whats wrong with this?

jQuery(document.body).append('<div id="wrapper-1"><div id="wrapper-2"></div></div>');

the browser will understand that is a child

Upvotes: 0

Related Questions