So, I have this HTML document
<!DOCTYPE html>
<html>
<head>
<title>TestPage</title>
<script src="script.js"></script>
</head>
<body>
<p id="test">Sample text</p>
</body>
</html>
With this JS file
window.addEventListener("load", MyFunction());
function MyFunction(){
document.getElementById("test").innerHTML = "it worked";
}
and ofcourse this doesn't work (the text isn't changed), since it loads the script before it actually loads the <p id="test"></p>
element (I think). It may seem strange, but I want to change the content of some elements, after everything has loaded. I have searched, but to no avail. I'm missing something obvious here probably, but I can't seem to figure it out. Any advice would be appreciated!
You're calling the function in the setup for your "load" event.
Did you mean:
window.addEventListener("load", MyFunction);
??
Try:
window.onload = function () {
MyFunction()
}
function MyFunction(){
document.getElementById("test").innerHTML = "it worked";
}
Simply add this to your body tag :
<body onload=myFunction()>
function myFunction(){
document.getElementById("test").innerHTML = "it worked";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.