[JS]cannot read property ‘getElementsByTagName‘ of null
程序员文章站
2022-06-07 12:36:11
...
事件说明:
看了一个轮播图的演示,想自己动手试一下。把html和css代码写好后,在JS中调用元素时出现了点不愉快。
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" type="text/css" href="css1.css">
<script type="text/javascript" src="js2.js"></script>
</head>
<body>
<div class="main" id="main">
<div class="nav" id="nav0">
<div class="nav1 active1">首页</div>
<div class="nav1">点击看看</div>
<div class="nav1">会自动的</div>
<div class="nav1">我的网站</div>
</div>
<div class="banner" id="pic0">
<div class="pic pic1 picact1"></div>
<div class="pic pic2"></div>
<div class="pic pic3"></div>
<div class="pic pic4"></div>
</div>
</div>
</body>
var index=0,
navs=document.getElementById("nav0").getElementsByTagName("div"),
size=navs.length;
console.log(size)
想先测试一下是否取到元素了,所以在console里测试了一下,结果:
查了一下,以为是因为导航栏部分没有设置id导致。
后来发现是script放在了head中,如果没有设置window.onload,那么JS在html加载之前就会被解析,相应的就取不到html中的元素了。
window.onload=function(){
var index=0,
navs=document.getElementById("nav0").getElementsByTagName("div"),
size=navs.length;
console.log(size)
}
这样运行代码就OK啦。
推荐阅读
-
Vue报错:Uncaught TypeError: Cannot assign to read only property’exports‘ of object
-
npm ERR! Cannot read property 'path' of null
-
js报错 Cannot read property 'getAttribute' of null
-
微信小程序报Cannot read property 'setData' of undefined的错误
-
webpack报错Cannot read property 'presetToOptions' of undefined
-
Extjs4---Uncaught TypeError: Cannot read property ‘items’ of undefined
-
JavaScript Uncaught TypeError: Cannot read property 'value' of null
-
Cannot read property 'tap' of undefined
-
Vue报错:Uncaught TypeError: Cannot assign to read only property’exports‘ of object’#
-
Property or field ‘XXX‘ cannot be found on null