问题
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