0

I am trying to change the style of element by using JavaScript, however, I get this error when I try to: test.html:4 Uncaught TypeError: Cannot read property 'style' of null at test.html:4

This is my code:

<html>
<head>
  <script type="text/javascript">
    document.getElementById("test").style.marginTop="20px";
  </script>
</head>
<body>
  <p id="test">
    this is a test
  </p>
</body>
</html>

I am new to JavaScript, so sorry if I am doing something completely wrong, but everything seems fine to me. I'm probably doing some dumb mistake.

MTMaster
  • 7
  • 3
  • Possible duplicate of [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Sebastian Simon Jun 14 '17 at 01:26

4 Answers4

1

Your JavaScript code is executed before the document with p tag has been created.
To fix that put you code at the bottom of the body tag or in document load completed event.

<html>
  <head>
  </head>
  <body>
    <p id="test">
      this is a test
    </p>
    <script type="text/javascript">
      document.getElementById("test").style.marginTop="20px";
    </script>
  </body>
</html>

Additionally, placing scripts at the bottom of the 'body' element improves the display speed, because script compilation may slows down the display.

MaxZoom
  • 7,619
  • 5
  • 28
  • 44
0

It's a runtime error. Your JavaScript is attempting to access an element that doesn't yet exist when the statement is executed. Move your JavaScript code block to the bottom of your document.

Major Productions
  • 5,914
  • 13
  • 70
  • 149
0

The problem here will be that the script is executed before the div with id="test" is on the page. You can either move the code to the bottom of the page or add an event listener for when the window is loaded like so:

<script type="text/javascript">
    window.addEventListener('load', function(){
        document.getElementById("test").style.marginTop="20px";
    });
</script>
Thomas Maddocks
  • 1,355
  • 9
  • 24
0

wrap it up in a event listener like this

window.onload = function(event){
  document.getElementById("test").style.marginTop="20px";
}

so when element becomes available you can use it. Currently element is not available as it tries to get element before page loads. so to run the code when element is available wrap it like above.

Krishna Satya
  • 775
  • 2
  • 9
  • 21