最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How can I read a HTML comment located outside of <html> using JavaScript? - Stack Overflow

programmeradmin4浏览0评论

I have a HTML ment outside of the DOM root node which I need to read:

<html>
   ... other stuff
</html>
<!-- The ment I want to read -->

Can I do this with JavaScript somehow?

I have a HTML ment outside of the DOM root node which I need to read:

<html>
   ... other stuff
</html>
<!-- The ment I want to read -->

Can I do this with JavaScript somehow?

Share Improve this question edited Sep 21, 2009 at 17:49 Shog9 160k36 gold badges235 silver badges240 bronze badges asked Sep 21, 2009 at 14:34 Tomas FTomas F 7,6066 gold badges29 silver badges36 bronze badges 1
  • 1 They're actually HTML ments – nickytonline Commented Sep 21, 2009 at 16:33
Add a ment  | 

3 Answers 3

Reset to default 6

I did some testing on this and discovered that any HTML beyond </html> is appended to the <body> during parsing. So, in all browsers I tested (IE6/7, FF3, Opera10, Chrome2), the ment was accessible as document.body.lastChild and its contents can be retreived via document.body.lastChild.data.

The DOM standard for the #document node (the logical root of a DOM document) allows exactly one element node (i.e. one <HTML>), but many ment nodes (and other, more esoteric node types). As such, we should expect

document.lastChild

to be the ment node you want in this instance. Oddly, this does not work (at least in Safari 4).

Putting a ment node before the HTML node is fine in my tests. In this case, document.childNodes.length is 2, and document.firstChild is the ment. Putting a ment after the HTML node seems to be inserted in the wrong place in the DOM - document.childNodes.length remains at 1, and the node in the DOM inspector is seen as the last child of the BODY node. However, I can't find that node using the DOM API at all!

This seems to be an oddity in (at least) the Safari implementation of DOM. A quick test using Firefox shows that it can't even find a ment node if it's the first entry in the document!

Edit: OK, as per Aaron's ment and some more pondering, it's likely that the parser for the page is just discarding the nodes during parsing. I'm no longer certain this is a bug, but I can't find anything in the (XML) spec that allows parsers to discard entire ment nodes - only their textual content.

There is a jQuery plugin for this problem: http://www.bennadel./index.cfm?dax=blog:1563.view

It seems that

objChildNode.nodeType === 8

is the point!

发布评论

评论列表(0)

  1. 暂无评论