这是解析函数
Ajax:
{
ParseHTML: function(aHTMLString)
{
var html = document.implementation.createDocument("http://www.w3.org/1999/xhtml", "html", null),
body = document.createElementNS("http://www.w3.org/1999/xhtml", "body");
html.documentElement.appendChild(body);
body.appendChild(Components.classes["@mozilla.org/feed-unescapehtml;1"]
.getService(Components.interfaces.nsIScriptableUnescapeHTML)
.parseFragment(aHTMLString, false, null, body));
return body;
}
}
这里我尝试在 http 响应中使用解析(以净化代码):
var newdoc = Ajax.ParseHTML(o.responseText);
但是,当我尝试使用时:
newdoc.getElementById('teste');
它返回错误:TypeError: newdoc.getElementById is not a function
我做错了什么吗?和documentType有什么关系吗?
此外,此函数还会删除 a
标记中的所有 href=""
属性,例如,问题可能与...相关...
最佳答案
getElementById
仅在 document
对象上定义,因为 ID 在文档中必须是唯一的。因此,在元素对象上定义 getElementById
没有意义。
以下方法有效:
newdoc.querySelector('#teste');
newdoc.ownerDocument.getElementById('teste');
至于创建文档,您可能是interested in the DOMParser ,或者想使用document.implementation.createHTMLDocument
(使用 HTML
)。
关于javascript - 使用 parseFragment 在 Firefox 插件中解析 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9618627/