从字符串创建DOM文档,不使用JQuery [英] Create a DOM document from string, without JQuery

查看:169
本文介绍了从字符串创建DOM文档,不使用JQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在寻找从字符串中在javascript中创建 DOM文档的方法,但不使用Jquery。
有没有办法这样做? [我会这么认为,因为Jquery可以做到!]

We're looking for ways to create a DOM document in javascript from a string, but without using Jquery. Is there a way to do so? [I would assume so, since Jquery can do it!]

对于那些好奇的人,我们不能使用Jquery,因为我们在一个上下文中这样做Chrome应用程序的内容脚本,并且使用Jquery只会使我们的内容脚本太重。

For those curious, we can't use Jquery, becase we're doing this in the context of a Chrome application's content script, and using Jquery would just make our content script too heavy.

推荐答案

如果你还在寻找一个anwer,对于其他任何人来说,我一直在尝试自己做同样的事情。看来你想看看javascript的DOMImplementation:

In case you're still looking for an anwer, and for anyone else coming accross it, I just have been trying to do the same thing myself. It seems you want to be looking at javascript's DOMImplementation:

http://reference.sitepoint.com/javascript/DOMImplementation

此处对兼容性的引用很少,但它得到了相当好的支持。

There are few references to compatibility as well here, but it's fairly well supported.

本质上,要创建一个要操作的新文档,您需要创建一个新的Doctype对象(如果您要输出一些基于标准的东西)然后创建使用新创建的Doctype变量的新文档。

In essence, to create a new document to manipulate, you want to create a new Doctype object (if you're going to output some standards based stuff) and then create the new Document using the newly created Doctype variable.

有多个选项可以放入doctype和文档中,但是如果要创建HTML5文档,似乎你想把它们中的大多数留作空字符串。

There are multiple options to be put into both the doctype and the document, but if you're creating an HTML5 document, it seems you want to leave most of them as blank strings.

示例(新的HTML5 DOM文档):

Example (New HTML5 DOM Document):

var doctype = document.implementation.createDocumentType( 'html', '', '');

var dom = document.implementation.createDocument('', 'html', doctype);

新文档现在如下所示:

<!DOCTYPE html>
<html>
</html>

示例(新的XHTML DOM文档):

Example (New XHTML DOM Document):

var doctype = document.implementation.createDocumentType(
    'html',
    '-//W3C//DTD XHTML 1.0 Strict//EN',
    'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'
);

var dom = document.implementation.createDocument(
    'http://www.w3.org/1999/xhtml',
    'html',
    doctype
);

因此,您需要填写其余部分。您可以像更改

So it's up to you to populate the rest of it. You could do this as simply as changing

dom.documentElement.innerHTML = '<head></head><body></body>';

或者更严格:

var head = dom.createElement( 'head' );
var body = dom.createElement( 'body' );
dom.documentElement.appendChild(head);
dom.documentElement.appendChild(body);

全部。

这篇关于从字符串创建DOM文档,不使用JQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆