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

JqueryHtmlAppend

Jquery Problem Overview


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.

Jquery Solutions


Solution 1 - Jquery

jQuery methods returns the set they were applied on.

Use .appendTo:

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

Solution 2 - Jquery

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

Solution 3 - Jquery

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

Solution 4 - Jquery

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 - Jquery

Using jQuery appendTo try this:

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

Solution 6 - Jquery

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionwaxicalView Question on Stackoverflow
Solution 1 - JqueryDidier GhysView Answer on Stackoverflow
Solution 2 - JquerythecodeparadoxView Answer on Stackoverflow
Solution 3 - JqueryxdazzView Answer on Stackoverflow
Solution 4 - JqueryShankarSangoliView Answer on Stackoverflow
Solution 5 - Jquerysinemetu1View Answer on Stackoverflow
Solution 6 - JqueryAbhishekView Answer on Stackoverflow