Access comment nodes outside of the <html> tag

I am developing a chrome extension that reads html comments from a page and displays them in an action popup.

However, I don't know how (and if it is possible) to get some of the comments that are before and after the tag <html>

. For example:

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

      

In jQuery, $("html").before()

and $("html").after()

both return the same as $("html")

.

Is it possible to get these types of comments with jQuery or pure Javascript?

Edit: the comments page 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


source to share


3 answers


With this document:

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

      

You will receive the first comment like this:

document.firstChild.nodeValue

      



The second comment looks like this:

document.childNodes[2].nodeValue

      

To get all comments under 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);
    }
}

      

+4


source


document.firstChild

should do it.



0


source


$("html").siblings();

This will return all elements of the dom object at the same level as the html tag I believe. I wanted to validate using a JSfiddle, but now I am getting Javascript errors on my website using IE8. I can confirm later when I get home if that doesn't work for you when testing.

0


source







All Articles