jQuery - Appending a div to body, the body is the object?

106,122

Solution 1

jQuery methods returns the set they were applied on.

Use .appendTo:

var $div = $('<div />').appendTo('body');
$div.attr('id', 'holdy');

Solution 2

    $('body').append($('<div/>', {
        id: 'holdy' 
    }));

Solution 3

$('</div>').attr('id', 'holdy').appendTo('body');

Solution 4

Instead use use appendTo. append or appendTo returns a jQuery object so you don't have to wrap it inside $().

var holdyDiv = $('<div />').appendTo('body');
holdyDiv.attr('id', 'holdy');

.appendTo() reference: http://api.jquery.com/appendTo/

Alernatively you can try this also.

$('<div />', { id: 'holdy' }).appendTo('body');
               ^
             (Here you can specify any attribute/value pair you want)

Solution 5

Using jQuery appendTo try this:

var holdyDiv = $('<div></div>').attr('id', 'holdy');
holdyDiv.appendTo('body');
Share:
106,122
waxical
Author by

waxical

Updated on March 24, 2020

Comments

  • waxical
    waxical about 4 years

    When I'm adding a div to body, it's returning the body as the object and then whenever I use that - it's obviously using body. Bad.

    Code:-

    var holdyDiv = $('body').append('div');
    $(holdyDiv).attr('id', 'holdy');
    

    The 'id' of holdy is now being added to body... eh? What am I doing wrong.