问题
I've got a problem with retrieving link to the body tag. I've tried:
document.body
, unfortunately it is null- search body by tagName while enumerating childs of document, it's found only the head tag :(
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