getElementsByTagName does not seem to work

别说谁变了你拦得住时间么 提交于 2019-12-12 03:11:58

问题


Can someone please explain why my code is not working !!

When I get the element By Id it works perfectly fine. But the same method with getElementsByTagName() does not.

Also if I use querySelector(), it works. However if I use querySelectorAll() the same error returns.

test.html:15 Uncaught TypeError: Cannot set property 'color' of undefined

here is my code:

<DOCTYPE! html>
<html>
<head>

</head>

<body>
<h1>Hello World</h1>
<p id="par">Hello World</p>

<script>
var par = document.getElementById('par');
par.style.color = "red"
var heading = document.getElementsByTagName("h1");
heading.style.color = "red"
</script>


</body>
</html>

回答1:


As you can clearly see document,getElementsByTagName returns an array of elements, not a single element.

So you have to follow proper indexing otherwise it will throw an exception as in your case.



来源:https://stackoverflow.com/questions/38576698/getelementsbytagname-does-not-seem-to-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!