如果你确认你的代码没有写错,但输出来是null,那么你的问题可能是:
你的js写在了body前面,在执行该代码时该元素还没有渲染,在文档中并不存在被选中的元素
这也是我们要把js引用写在文档后的原因
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script>
console.log(document.getElementById("d1"));
</script>
</head>
<body>
<div id="d1"></div>
</body>
</html>
解决方案:script扔body后面即可
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="d1"></div>
</body>
<script>
console.log(document.getElementById("d1"));
</script>
</html>
网友评论