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.

1

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This is the best answer but you need to put the script tag before the body closing tag.
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.

Comments

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.

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.