开发者

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?


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.


or Better yet..

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


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

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

http://jsfiddle.net/3xkXQ/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜