Document.body in Opera

家住魔仙堡 提交于 2019-12-12 05:48:17

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/6516547/document-body-in-opera

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!