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

waxical picture waxical · Feb 2, 2012 · Viewed 99.1k times · Source

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.

Answer

Didier Ghys picture Didier Ghys · Feb 2, 2012

jQuery methods returns the set they were applied on.

Use .appendTo:

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