Saturday 29 June 2019

javascript - getElementById() work in html file but not in js file




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







Title






Some text








JS file



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

Answer




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";
});


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...