Access comment nodes outside <html> tag

2020-04-10 15:17发布

I'm developing a chrome extension that reads html comments from a page and render them in an action popup.

However, I don't know how to (and if it's possible) to fetch some comments that are before and after the <html> tag. For example:

<!-- test test test -->
<DOCTYPE html>
<html>
...
</html>

In jQuery, $("html").before() and $("html").after() both returns the same as $("html").

Is it possible do fetch those types of comments using either jQuery or pure Javascript?

Edit: the page with the comments looks like this:

<!-- Comment I'd like to fetch -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-us" lang="en-us" >
<head>
<title>Featured Designers for WOMEN</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> 
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<meta http-equiv="Content-Style-Type" content="text/css" />

3条回答
家丑人穷心不美
2楼-- · 2020-04-10 15:27

With this document:

<!-- comment 1 -->
<!DOCTYPE html>
<!-- comment 2 -->
<html>
<body>
hello world
</body>
</html>

You get the first comment like this:

document.firstChild.nodeValue

The second comment is found like this:

document.childNodes[2].nodeValue

To get all comments underneath document:

var nodes = document.childNodes;
for (var i = 0, len = nodes.length; i !== len; ++i) {
    if (nodes[i].nodeType === 8) {
        console.log('Found comment' + nodes[i].nodeValue);
    }
}
查看更多
迷人小祖宗
3楼-- · 2020-04-10 15:27

document.firstChild should do it.

查看更多
家丑人穷心不美
4楼-- · 2020-04-10 15:44

$("html").siblings(); This will return all the dom object elements at the same level as the html tag I believe. I wanted to confirm by using JSfiddle but I'm receviing Javascript errors on their website using IE8 right now. I can confirm later when I get home if it doesn't work for you in your testing.

查看更多
登录 后发表回答