我在其他人的帖子中找不到我的问题的答案,所以这里是: getElementById在Java脚本文件中返回null(也在控制台中测试时),但在html文件中工作
HTML文件
<!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文件
var title = document.getElementById('stuff');
console.log(title);
title.style.color = "#D4F34A";
答案 0 :(得分:1)
您可以像这样为文档事件DOMContentLoaded
事件添加回调函数,然后在该函数中执行所需的代码:
//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";
});