Jul*_*oux 22 javascript document
我们正在寻找从字符串中在javascript中创建DOM文档的方法,但不使用Jquery.有办法吗?[我会这么认为,因为Jquery可以做到!]
对于那些好奇的人,我们不能使用Jquery,因为我们是在Chrome应用程序的内容脚本环境中执行此操作,而使用Jquery会使我们的内容脚本过于繁重.
apr*_*kur 22
https://developer.mozilla.org/en-US/docs/Web/API/DOMParser
var parser = new DOMParser();
var doc = parser.parseFromString("<html_string>", "text/html");
Run Code Online (Sandbox Code Playgroud)
(结果doc变量是documentFragment对象).
小智 16
如果你还在寻找一个anwer,并且对于其他任何人来说,我只是一直试图自己做同样的事情.看来你想看看javascript的DOMImplementation:
http://reference.sitepoint.com/javascript/DOMImplementation
这里很少提及兼容性,但它得到了相当好的支持.
实质上,要创建要操作的新文档,您需要创建一个新的Doctype对象(如果要输出一些基于标准的东西),然后使用新创建的Doctype变量创建新文档.
doctype和document都有多个选项,但是如果你要创建一个HTML5文档,似乎你想把它们中的大多数留作空白字符串.
示例(新HTML5 DOM文档):
var doctype = document.implementation.createDocumentType( 'html', '', '');
var dom = document.implementation.createDocument('', 'html', doctype);
Run Code Online (Sandbox Code Playgroud)
新文档现在看起来像这样:
<!DOCTYPE html>
<html>
</html>
Run Code Online (Sandbox Code Playgroud)
示例(新的XHTML DOM文档):
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
);
Run Code Online (Sandbox Code Playgroud)
所以由你来填充剩下的部分.你可以像改变那样做
dom.documentElement.innerHTML = '<head></head><body></body>';
Run Code Online (Sandbox Code Playgroud)
或者更严格:
var head = dom.createElement( 'head' );
var body = dom.createElement( 'body' );
dom.documentElement.appendChild(head);
dom.documentElement.appendChild(body);
Run Code Online (Sandbox Code Playgroud)
全都是你的.
| 归档时间: |
|
| 查看次数: |
20150 次 |
| 最近记录: |