-2

i cannot find answer to my question in someone else post so here it is: getElementById return null in java script file (also while testing in console) but work in html file

HTML file

<!DOCTYPE html>
<html>
   <head>
      <title>Title</title>
      <link rel="stylesheet" href="css/style.css">
      <script src="js/app.js"></script>

   </head>
   <body>

      <p id="stuff">Some text</p>

   </body>
</html>

JS file

var title = document.getElementById('stuff');
console.log(title);
title.style.color = "#D4F34A";
xyz
  • 196
  • 10

1 Answers1

1

You can add a callback function for the document event DOMContentLoaded event like so, and inside that function do your desired code:

//Add this into your script file, and anything you want to have execute once the document
//is fully loaded go inside of the function
document.addEventListener("DOMContentLoaded", function(event) {
    var title = document.getElementById('stuff');
    console.log(title);
    title.style.color = "#D4F34A";
});
Ryan Wilson
  • 7,490
  • 1
  • 17
  • 31