开发者

Document.body in Opera

开发者 https://www.devze.com 2023-03-16 06:22 出处:网络
I\'ve got a problem with retrieving link to the body tag. I\'ve tried: document.body, unfortunately it is null

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;
     开发者_StackOverflow中文版   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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号