views:

45

answers:

2

How can I move an element to the end of the body?

Using jQuery, I want some given element to be moved to the body, preferably to be the last element contained by it.

Imagine the following would be valid:

$('#myElement').moveToTheEndOfTheBody();

Thanks!

+7  A: 

Use:

$('#myElement').appendTo(document.body);

.appendTo()

Description: Insert every element in the set of matched elements to the end of the target.

jAndy
$(document.body).append( $('#myElement')); also works :) (more so if myElement is already as a var or just created, like var `$myElem = $('<div />'); $(document.body).append( $myElem );` )
Dan Heberden
`document.body` could be replaced by `"body"`
Anpher
@Dan - Both will work, this is one of many things jQuery normalizes cross-browser. In any case, `document.body` is faster, that's what I'd go with.
Nick Craver
@Gert G: they are both _jQuerish_ (just pronounced that out-loud, lol).. its all about what you want in the end. If you are working with body or appending multiple things like `$(document.body).append($elem1).append($elem2);` then you want document.body returned.. but if you want to keep working with elem1 for instance, then the answered version would be better: `$elem1.appendTo(document.body).fadeIn(2000).html('chaining rocks')'` - and that, my friend, is the jQuery way :p
Dan Heberden
A: 

this would remove the object from the current location and put it at the end of the body..

$(document.body).append( $('#selector').detach() );
Gaby
This would add the literal text "#myElement" to the body, [`.append()`](http://api.jquery.com/append/) does not take a selector, you can see this here: http://jsfiddle.net/7GcXZ/ One further note, use `document.body`, it's much faster.
Nick Craver
oups .. very correct.. sorry about this.. corrected it now :)
Gaby