3

i have this jquery script:

$('#add').click(function(){
    $('<div class="drag" style="left:20px;"/>')
        .text( num++ )
        .appendTo( document.body )
        .css({ 
            top: $( window ).height() - 500 , 
            left:$( window ).width() - 500
        });
});

this will create: <div class="drag" style="left:20px;"/></div>

what i am interested in creating is this:

<div class="drag" style="left:20px;"/>
    <div class="handle SE">
    </div>
</div>

if i do this:

...
$('<div class="drag" style="left:20px;"/><div class="handle SE">')
.text( num++ )
...

jquery will create 2 separate di'vs and not nested.

any ideas?

thanks

Sliq
  • 15,937
  • 27
  • 110
  • 143
Patrioticcow
  • 26,422
  • 75
  • 217
  • 337

3 Answers3

8

Use .wrap():

$('<div class="handle SE">')
  .text(num++)
  .appendTo(document.body)
  .wrap('<div class="drag" style="left:20px;"/>);

Working example at http://jsfiddle.net/alnitak/r4Dz6/

In this particular example it's neccesary to call .appendTo(document.body) before the wrap is done because .wrap() returns the original element. Calling .appendTo last would result in the newly wrapped parent element getting removed from the hierarchy.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
2

Try:

var outer = $('<div class="drag">').text('foo');
var inner = $('<div class="handle SE">').text('bar');

$(outer).append(inner);
$(outer).appendTo('body');
Ayman Safadi
  • 11,502
  • 1
  • 27
  • 41
0

You can use $('<div class="drag"><div class="handle"></div></div>')

Demo: http://jsfiddle.net/VaKAw/

Edit: actualy you've put / at the end of first div:

$('<div class="drag" style="left:20px;"/><div class="handle SE">'),

which made them not nested, without it works as expected: http://jsfiddle.net/nbT8m/

welldan97
  • 3,071
  • 2
  • 24
  • 28