Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 217
waxical Avatar asked Feb 02 '12 15:02

waxical


People also ask

How append a div in another div using jQuery?

First, select the div element which need to be copy into another div element. Select the target element where div element is copied. Use the append() method to copy the element as its child.

Can you append to a div?

HTML code can be appended to a div using the insertAdjacentHTML() method. However, you need to select an element inside the div to add the code. This method takes two parameters: The position (in the document) where you want to insert the code ('afterbegin', 'beforebegin', 'afterend', 'beforeend')

What is append in jQuery?

jQuery append() Method The append() method inserts specified content at the end of the selected elements. Tip: To insert content at the beginning of the selected elements, use the prepend() method.


1 Answers

jQuery methods returns the set they were applied on.

Use .appendTo:

var $div = $('<div />').appendTo('body'); $div.attr('id', 'holdy'); 
like image 140
Didier Ghys Avatar answered Oct 18 '22 09:10

Didier Ghys