Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript to grab Javascript comments within <head>

Tags:

javascript

I have a page that begins as follows:

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

I would like to grab the 12036 number here and to display it within an absolutely positioned DIV at the bottom right of my screen. My intention here is to either to use it as a bookmarklet or as a Greasemonkey script.

The purpose of this is that the number represents a PAGE ID that we use reference internally.

I started off using:

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

But I could not progress any further.

Can anyone assist here?

like image 410
rlsaj Avatar asked Nov 29 '11 04:11

rlsaj


1 Answers

This will work in latest browsers but you will need to modify it to suit older browsers...

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

To position it at the bottom corner of your screen...

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

elem.id = 'id-display';

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

document.body.appendChild(elem);

...and a touch of CSS...

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

JSBin.

like image 80
alex Avatar answered Nov 06 '22 08:11

alex