简体   繁体   English

如何使用纯Javascript将未知HTML括在div中?

[英]How do you enclose unknown HTML in a div with plain Javascript?

I have an HTML page that has varying types of content. 我有一个HTML页面,其中包含各种类型的内容。 I would like to make a javascript function that when run encloses anything inside the <body> tag with a <div id="content-container"> . 我想制作一个JavaScript函数,在运行时将<body>标记内的所有内容括入<div id="content-container"> Then I want to be able to add a <div id="verifying"></div> that new <div> . 然后,我希望能够添加一个<div id="verifying"></div>新的<div> I think I know how to do this with jQuery, but I need to do it with plain Javascript. 我想我知道如何使用jQuery,但是我需要使用普通的Javascript来实现。

Any idea as to how this would be done? 关于如何做到这一点的任何想法吗?

This is how I might do it. 这就是我可能会做的。

var body = document.body;

var contentContainer = document.createElement('div');
contentContainer.id = 'content-container';

var node;

while (node = body.firstChild) {
    contentContainer.appendChild(node);
}

body.appendChild(contentContainer);

var verifying = document.createElement('div');
verifying.id = 'verifying';
contentContainer.appendChild(verifying);

jsFiddle . jsFiddle

I haven't tested, but I imagine that you can take the innerHTML of document and set it to be itself along with whatever wrapper string (or div) you want. 我还没有测试,但是我想您可以获取文档的innerHTML并将其设置为所需的任何包装字符串(或div)本身。

Something along the lines of: 类似于以下内容:

body = methodToLocateBodyInTheDom();
body.innerHTML = "<div id='content-container'>" + body.innerHTML + "</div>"

There are probably better ways, but I think something of that nature sure work. 可能有更好的方法,但是我认为这种性质的方法一定可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM