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.
$('body').append($('<div/>', {
id: 'holdy'
}));
var $div = $('<div />').appendTo('body');
$div.attr('id', 'holdy');
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)
Using jQuery appendTo try this:
var holdyDiv = $('<div></div>').attr('id', 'holdy');
holdyDiv.appendTo('body');
$('</div>').attr('id', 'holdy').appendTo('body');
Source: Stackoverflow.com