-1

How can I make a variable be the select Id in a getElement? When I tried it, it returned null. My code is shown below:

<html>
 <head>
 </head>
 <body>
   <p id = "test">hi</p>



  <script>
    var test = "test";
    document.getElementById(test).innerHTML = "complete";
  </script>

 </body
</html>
Dylan Ong
  • 54
  • 4
  • 2
    that's correct, it should work. btw your "body" closing tag is missing a `>`. – noahnu Apr 14 '18 at 23:42
  • You may want to execute your Javascript only after the page has finished loading. See also https://stackoverflow.com/questions/807878/javascript-that-executes-after-page-load – Jens Apr 14 '18 at 23:42

1 Answers1

2

That code seems to work just fine (with the exception of the unclosed body tag), here is a runnable version of the code, fixed:

<html>
 <head>
 </head>
 <body>
   <p id = "test">hi</p>



  <script>
    var test = "test";
    document.getElementById(test).innerHTML = "complete";
  </script>

 </body>
</html>

Remember, the js code is going to happen almost immediately, so you won't be able to see the "hi" part. If you want it to change after like 1 second, use this:

<html>
 <head>
 </head>
 <body>
   <p id = "test">hi</p>



  <script>
    var test = "test";
    setTimeout(function () {
        document.getElementById(test).innerHTML = "complete";
    }, 1000);
  </script>

 </body>
</html>

All I changed in that, is put the document.getElementById() into a setTimeout

Hope this helped.

Sheshank S.
  • 2,482
  • 2
  • 13
  • 33