0

My script wont run or the document.getElementById("toMove"); doesn't seem to catch the element. Its very basic javascript but I cant understand why its not working.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>test</title>
    <style>
    #toMove
    {
        background-color:lightblue;
        position:absolute;
    }
    </style>
        <script>
        var elem = document.getElementById("toMove");
        elem.style.margin = "600px";
    </script>   
</head>
    <body>  
<div id="toMove" style="margin:200px; font-size:26px;"> Hello World</div> 
    </body> 

Thanks

djcj
  • 149
  • 2
  • 15

5 Answers5

1

Close your the tag properly. Problem is that when your scripts executes your element toMove does not exists in DOM

Wrap your code in window.onload. The function execute a JavaScript when a page is finished loading.

 window.onload = function(){
    var elem = document.getElementById("toMove");
    elem.style.margin = "600px";
 }

OR, Simply write your script at after you HTML declartion

Satpal
  • 132,252
  • 13
  • 159
  • 168
1

The problem is that this script must run once the DOM is ready (all elements rendered in the browser) Wrap the script like described here:

pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it

Or if you use jquery with

$('document').ready(function(){});

Community
  • 1
  • 1
vanthome
  • 4,816
  • 37
  • 44
0

You must close head tag correctly.

</head>

And also do the code of Satpal.

Gaucho_9
  • 265
  • 1
  • 3
  • 11
0

This will work.

<!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <title>test</title>
        <style>
        #toMove
        {
            background-color:lightblue;
            position:absolute;
        }
        </style>

    </head
        <body>  
    <div id="toMove" style="margin:200px; font-size:26px;"> Hello World</div> 
        </body> 
         <script>
             var elem = document.getElementById("toMove");
              elem.style.margin = "500px";
        </script>  
        </html>
Tom Cruise
  • 1,395
  • 11
  • 30
  • 58
0

There's a couple of reasons why it's not working

  1. You need to close the <head> tag properly
  2. The point at which your script runs, the element with the id toMove does not yet exist in the DOM (Document Object Model)

Solving number 1 should be easy enough, just change </head to </head>. To solve number 2, you need to ensure that the script fires after the element with id toMove exists in the DOM. You can do this by hooking up your script to fire when the window has finished loading. The code below sets up a function to fire when the window has finished loading

window.onload = function(){
   var elem = document.getElementById("toMove");
   elem.style.margin = "600px";
}
Russ Cam
  • 124,184
  • 33
  • 204
  • 266