Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

css

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>
like image 661
mcbeav Avatar asked May 18 '26 23:05

mcbeav


2 Answers

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.

like image 71
Cᴏʀʏ Avatar answered May 21 '26 12:05

Cᴏʀʏ


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/

like image 37
Jason McCreary Avatar answered May 21 '26 13:05

Jason McCreary