var imgElement = document.getElementById("box02");
function fun1() {
alert(imgElement); // null
}
將賦值語句移入函數內部則正常。
<head> 或 <body> 開始處執行,目標元素尚未解析,getElementById 返回 null。window.onload、DOMContentLoaded 或 <script> 放在 </body> 前。let/const 防止提升。console.log(document.getElementById(...)) 觀察時間點。