aprea
aprea

Reputation: 109

jQuery .after won't insert <body> element

Why doesn't this work?

var newbody = "<body><div>hello</div></body>";

$("body").remove();
$("head").after(newbody);

All i get after that is:

</head>
<div>hello</div>

How can i get it to stop dropping the body tags?

Upvotes: 3

Views: 2708

Answers (3)

Andy E
Andy E

Reputation: 344575

This is because of how jQuery's HTML insertion functions work with before() and after(). IIRC, they create a temporary element and set the innerHTML of the newly created element, before transferring the elements to where they're supposed to be. Since the <body> tag can only be a child of the <html> element, the major browsers remove it from the source. However, when you append elements to the <html> element, a new <body> element should be implied anyway.

If you're unsure, you could use the standard DOM function createElement() to create the body and use append() to add the element as a child of html():

var newbody = document.createElement("body");
$(newbody).html("<div>hello</div>");
$("body").remove();
$("html").append(newbody);

Working demo: http://jsfiddle.net/3dSN4/ (shows it working with a class name)

That all being said, there aren't really any reasons I can think of for removing and creating a new body element. You should just manipulate the existing body element in the required manner as to minimize any potential browser issues arising from removing the body.

Upvotes: 5

netbrain
netbrain

Reputation: 9304

or Better yet..

var newbody = "<body><div>hello</div></body>";
$("body").replaceWith(newbody);

Upvotes: 2

Farshid Zaker
Farshid Zaker

Reputation: 1990

var newbody = "<body><div>hello</div></body>";

$("body").html("");
$("body").append(newbody);

http://jsfiddle.net/3xkXQ/

Upvotes: 0

Related Questions