Saturday, June 29, 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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...