这是我一直遇到的一些困难.我有一个本地客户端脚本,需要允许用户获取远程网页并搜索结果页面的表单.为了做到这一点(没有正则表达式),我需要将文档解析为完全可遍历的DOM对象.
我想强调的一些限制:
getElementsByTagName需要提供DOM API等.假设我在变量中有一个完整的HTML文档字符串(包括DOCTYPE声明)html,这是我到目前为止所尝试的:
var frag = document.createDocumentFragment(),
div = frag.appendChild(document.createElement("div"));
div.outerHTML = html;
//-> results in an empty fragment
div.insertAdjacentHTML("afterEnd", html);
//-> HTML is not added to the fragment
div.innerHTML = html;
//-> Error (expected, but I tried it anyway)
var doc = new ActiveXObject("htmlfile");
doc.write(html);
doc.close();
//-> JavaScript executes
Run Code Online (Sandbox Code Playgroud)
我也尝试从HTML中提取<head>和<body>节点,并将它们添加到<HTML>片段内的元素,仍然没有运气.
有没有人有任何想法?