Javascript to capture Javascript comments in <head>

I have a page that starts as follows:

<html>
        <head>
        <!-- 12036,2011-11-29/11:02 -->
        <title>Products & Services</title>

I would like to take the number 12036 here and display it in an absolutely positioned DIV in the lower right corner of the screen. My intention here is to use it as a bookmarklet or as a Greasemonkey script.

The purpose of this is that the number is the PAGE identifier that we use for internal use.

I started using:

var x = document.getElementsByTagName('head').innerHTML;

But I could not move on.

Can anyone help here?

+5
source share
3 answers

This will work in recent browsers, but you will need to change it to match older browsers ...

var commentNode = [].slice.call(document.head.childNodes).filter(function(node) {
            return node.nodeType == 8;
          })[0],
    id = commentNode.data.match(/^\s*(\d+)/)[1];

...

var elem = document.createElement('div');

elem.id = 'id-display';

elem.appendChild(document.createTextNode(id));

document.body.appendChild(elem);

... CSS...

#id-display {
    position: fixed;
    bottom: 0;
    right: 0;
    background: #333;
    color: #fff;
    padding: 6px;
}

JSBin.

+6

, , var ele;

var div = document.getElementsByTagName('div')[0];

, var nodes = div.childNodes;

node, "8" .

for (var i=0; i<nodes.length; i++){
    if (nodes[i].nodeType === 8) {
        //Only comments go out to console.
        console.log(nodes[i]);
    }1
}

.

, - HTML .

+2

getElementsByTagName . , innerHTML - .

document.getElementsByTagName('head')[0].innerHTML

Instead of using, innerHTMLyou might consider using .childNodesand scrolling to search for comment nodes.

+1
source

All Articles