简体   繁体   中英

document.getElementById() is null

I have this piece of code. It is getting an error document.getElementById('foo') is null. Please help with this problem.

<script>
function doMove() {
    var foo=document.getElementById('foo');
    foo.style.left = (foo.style.left+10)+'px'; // pseudo-property code: Move right by 10px
    setTimeout(doMove(),20); // call doMove() in 20 msec
}
doMove();
</script>

</head>
<body>
<div id="foo" style="width:10px;">a</div>
</body>
</html>

That's because the object doesn't yet exist when the script is executed.

The simplest solution is to move your script at the end of the body.

Another solution is to wait for the DOM to be loaded :

window.addEventListener('load', doMove);

将代码粘贴在主体关闭标签之前的底部。

Try placing the script at the end of the document's body.

Like this:

<body>
<div id="foo" style="width:10px;">a</div>
<script>
function doMove() {
var foo=document.getElementById('foo');
     foo.style.left = (foo.style.left+10)+'px'; // pseudo-property code: Move right by 10px
     setTimeout(doMove(),20); // call doMove() in 20 msec
    }
    doMove();
</script>
</body>

The element does not yet exist when the script is run. A simple solution to your problem would be to move the call to doMove from the script and call it onload for the body tag like so:

<body onload="doMove()">

Or simply move the script below the div with id 'foo'.

If support for older versions of IE (pre IE9) 'addEventListener' is an alternative. Replace your call to doMove with this snippet:

window.addEventListener('load', doMove);

I have changed my code and written this. It is now reading document.getElementById('foo'). I want to move my div element every 20msec for that I have used setTimeout() but it doesn't do anything.

<body>
<div id="foo" style="width:10px;">a</div>
<script language="javascript">
function doMove() {
var foo=document.getElementById('foo');
     foo.style.left = parseInt(foo.style.left)+10+'px'; // pseudo-property code: Move right by 10px
     setTimeout(doMove,20); // call doMove() in 20 msec
    }
    doMove();
</script>
</body>
</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM