为什么用document.getElementById();
结果输出为空
原代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>dom</title>
<script src="006.js"></script>
</head>
<body>
<div id="c1">
<h1 id="c2">大大的标题</h1>
<ul>
</ul>
</div>
</body>
</html>
var qq =document.getElementById('c2');
console.log(qq);
剖析原因
因为<script src="006.js"></script>
放的太靠前了,
解决办法
把放在最后面,在解析完标题等用到的元素之后,再进行操作
解决后的代码
var qq =document.getElementById('c2');
console.log(qq);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>dom</title>
</head>
<body>
<div id="c1">
<h1 id="c2">大大的标题</h1>
<ul>
</ul>
</div>
<script src="006.js"></script>
</body>
</html>