0

In my example Iam looking for a way to identify a p element on window load:

The below shown code snippet gives the following error:
Uncaught TypeError: Cannot set properties of null (setting 'innerHTML');
=> I guess thats because on window the load the p element cannot be identified by the getelementid method. Thats because the javascript runs at first.

// example 1
<script>
      document.getElementById("myInputBox").innerHTML ="I should be the text content on window load";
</script>
 
<body>
   <p id="myInputBox">Iam the preset text content.</p>
</body>

So I tried the following to get closer:

  • Browser runs first through the code, but does not execute the changeText() function
  • Triggering the changeText() function afterwards works fine. => The getElementById method can work on the p element because its known at that time
//example 2
<script>
   function changeText()
{
      document.getElementById("myInputBox").innerHTML ="Iam the text content after button click.";
   }
</script>
 
<body>
   <p id="myInputBox">Iam the preset text content.</p>
   <button onclick="changeText()">Click me</button>
</body>

Does somebody know how to identify the p element on window load (example 1)?

KeepRunning85
  • 173
  • 10
  • 1
    you have to defer your javascript code, but am not sure if you can do on inline script, but you can make your script external though, link it and defer it, like so : ``` ``` – Y U K I M U R A Dec 21 '22 at 10:33

0 Answers0