简体   繁体   中英

document.getElementById('box').style.width=“10px”; Doesn't work?

I cannot seem to get this script to work. Can anyone please help? The DIV's width is not defined. It just stretches across the whole page.

<html>
<head>
<style type="text/css">
#box{
    height:100px;
    border:3px;
    border-style:solid;
    border-color:#000;
}
</style>
<script>
document.getElementById('box').style.width="10px";
</script>
</head>
<body>
<div id="box"></div>

Your script is running before the <div> is rendered on the page. Try it like this:

<html>
<head>
<style type="text/css">
#box{
    height:100px;
    border:3px;
    border-style:solid;
    border-color:#000;
}
</style>
</head>
<body>
    <div id="box"></div>

    <script type="text/javascript">
        document.getElementById('box').style.width="10px";
    </script>

</body>
</html>

And don't forget to close your <body> and <html> tags.

To prove that it is, look at this example. I moved the script back to the <head> section and changed the width setting to run when the window is finished loading.

<html>
<head>
<style type="text/css">
#box{
    height:100px;
    border:3px;
    border-style:solid;
    border-color:#000;
}
</style>

<script type="text/javascript">
    alert('test');

    window.onload = function() {
        document.getElementById('box').style.width="10px";
    }
</script>

</head>
<body>
    <div id="box"></div>
</body>
</html>

You'll see the 'test' alert message before the box is rendered.

The element does not exist on the page yet. JavaScript can not access/manipulate an element until it has been loaded in the DOM. You can overcome this by moving you <script> block to above the closing </body> . Or use an window.load event.

An example of the former using your code is here - http://jsfiddle.net/ycWxH/

if you will use jquery it is more easy to do that. that is if you will only use jquery framework here is the code

$('#box').height(10);

just a reminder, window.onload is fired when page fully loaded. refer to http://www.javascriptkit.com/dhtmltutors/domready.shtml

<script>
function doMyStuff() = {};


if ( document.addEventListener ) {
document.addEventListener( "DOMContentLoaded", doMyStuff, false );
} else if ( document ) {
document.attachEvent("onreadystatechange",function(){
        if ( document.readyState === "complete" ) {doMyStuff();}
});}
</script>

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