在 Gecko 中从字符串创建文档
我有一个字符串,例如
我想获取 #message 元素的内容,而无需自己解析 HTML。
我想也许我可以从 Gecko 中的字符串创建一个文档对象(这是针对 Firefox 的附加组件),但我没有看到任何简单的方法。
我注意到有一个 createDocument 方法,但这不需要细绳。我必须从文本中删除 部分,然后我又开始假设一些东西。
有人有什么想法吗?谢谢。
编辑:这似乎对我有用:
doc = document.implementation.createDocument( "http://www.w3.org/1999/xhtml", "html", null );
doc.firstChild.innerHTML = '<html><body><div id="message">Hello World!</div></body></html>';
node = doc.getElementById( "message" );
alert( node.innerHTML );
I have a string such as<html><body><div id="message">Hello World!</div></body></html>
and I would like to get the content of the #message element without parsing the HTML myself.
I thought maybe I could create a document object from a string in Gecko (this is for a Firefox add on) but I don't see any simple way.
I noticed that there is a createDocument method, but that doesn't take a string. I'd have to strip the <html>
portion from the text, and then again I'm starting to assume stuff.
Anyone have any ideas? Thanks.
EDIT: This seems to work for me:
doc = document.implementation.createDocument( "http://www.w3.org/1999/xhtml", "html", null );
doc.firstChild.innerHTML = '<html><body><div id="message">Hello World!</div></body></html>';
node = doc.getElementById( "message" );
alert( node.innerHTML );
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不喜欢回答我自己的问题,但这似乎对我有用:
Don't like answering my own question, but this seems to have worked for me:
你从哪里得到字符串?如果它是 XML,您可以使用
DOMParser
。否则,您必须创建一个 HTML 文档 - https://developer.mozilla.org/en/Parsing_HTML_From_Chrome< /a>.
仅使用 createDocument 的工作原理似乎很可疑,因为人们一直在使用更复杂的解决方案。
Where do you get the string from? If it's XML, you could get away with using
DOMParser
.Otherwise, you have to create an HTML document - https://developer.mozilla.org/en/Parsing_HTML_From_Chrome.
The fact that just using
createDocument
works seems suspicious, because people used more complicated solutions all this time.总是这样的语法吗?如果是这样,为什么不使用正则表达式呢?
Is it always that syntax? If so, why not use a regex?