glagola
glagola

Reputation: 2242

Document.body in Opera

I've got a problem with retrieving link to the body tag. I've tried:

  1. document.body, unfortunately it is null
  2. search body by tagName while enumerating childs of document, it's found only the head tag :(
  3. document.getElementsByTagName, return undefined

I'm trying to get link to the body tag in onload event handler. This is a HTML code of the page:

<html>
    <head>
        <title>Some page</title>
        <script src="/adv.js" type="text/javascript"></script>
    </head>
    <body>
        This is text
    </body>
</html>

Here the source code of adv.js:

(function () {

    var myRandom = function (min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    };

    var myFunction = function () {
        var newScriptAddr = '/adLoader.js?r=' + myRandom(1,1000000);

        var fileref = document.createElement('script');
        if (typeof fileref != "undefined")
        {
           fileref.setAttribute("type", "text/javascript");
           fileref.setAttribute("src", newScriptAddr);

           document.getElementsByTagName("head")[0].appendChild(fileref);
        }
    };

    if (window.onload)
    {
        var currOnLoad = window.onload;
        window.onload = function () {
            currOnLoad();
            myFunction();
        };
    }
    else
        window.onload = myFunction();

}) ();

Source code of adLoader.js:

(function () {

    var mainCnt = document.createElement('div');
    mainCnt.appendChild(document.createTextNode('The text'));

    var _body = document.body;

    if (!_body)
    {
        var htmlTag = document.documentElement;
        for(var i = 0; i < htmlTag.childNodes.length; i++)
        {
            if (htmlTag.childNodes[i].nodeName.toLowerCase() == 'body')
            {
                _body = htmlTag.childNodes[i];
                break;
            }
        }
    }

    if (!_body)
        _body = document.getElementsByTagName('BODY') [0];

    if (!_body)
        _body = document.getElementsByTagName('body') [0];

    if (_body)
        _body.appendChild(mainCnt);
    else
        alert('WTF!!');

}) ();

Browser is Opera 11.10 OS Ubuntu Linux. Is there way to get this link? My aim is to add div with position:fixed to the body tag.

Upvotes: 0

Views: 1361

Answers (2)

Quentin
Quentin

Reputation: 944546

myFunction() doesn't return a function, so you are assigning undefined to window.onload. You probably mean window.onload = myFunction;

Anyway, as written at the moment, the code runs immediately and the body element hasn't been reached.

Upvotes: 3

james li
james li

Reputation: 184

if the js code in head tag and the query the body tag before onload event, null should be got while browser just reading the head.

Upvotes: -1

Related Questions