[JS]cannot read property ‘getElementsByTagName‘ of null
2020-07-21 04:12
2727 查看
事件说明:
看了一个轮播图的演示,想自己动手试一下。把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啦。
相关文章推荐
- Cannot read property 'getElementsByTagName' of null解决办法
- js中出现Cannot read property 'nodeName' of null
- js事件处理程序 Uncaught TypeError: Cannot read property 'addEventListener' of null
- Uncaught TypeError: Cannot read property 'getElementsByTagName' of null
- 安卓Webview 加载网页 Uncaught TypeError: Cannot read property 'getItem' of null",
- echarts-all.js:1 Uncaught TypeError: Cannot read property 'getAttribute' of null
- js提示Uncaught TypeError: Cannot read property 'options' of null
- 关于js Uncaught TypeError: Cannot read property 'style' of null 问题
- Cannot read property 'getAttribute' of null
- JS 报错 Cannot read property 'appendChild' of null
- html创建canvas画布失败"cannot read property 'getContext' of null"
- 关于JS出现的Cannot read property 'XXX' of null错误
- cocos2d-js-----Uncaught TypeError: Cannot read property 'style' of null
- Uncaught TypeError: Cannot read property 'getItem' of null
- Cannot read property 'getElementsByTagName' of null
- uploadify的JS组件报错:Uncaught TypeError: Cannot read property 'queueData' of undefined
- Uncaught TypeError: Cannot read property 'length' of null
- 调用百度报Cannot read property 'lng' of null错误
- 写js点击事件时览器出现报错——Cannot set property 'onclick' of null,解决办法
- Uncaught TypeError: Cannot read property 'get' of undefined --echarts.min.js:12