hello
"; $("body").remove(); ...">

JQuery after will not insert the <body> element

Why is this not working?

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

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

All I get after this:

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

How can I make it stop losing body tags?

+3
source share
3 answers

This is due to the way jQuery HTML insertion functions work with before()and after(). IIRC, they create a temporary item and set up the innerHTMLnewly created item before moving items to where they should be. Since a tag <body>can only be a child of an element <html>, major browsers remove it from the source. However, when you add elements to an element <html>, in any case, the new element should be implied <body>.

, DOM createElement() append() html():

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

: http://jsfiddle.net/3dSN4/ (, )

, , body. , , .

+5

..

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

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

http://jsfiddle.net/3xkXQ/

0
source

All Articles