简体   繁体   中英

getElementsByTagName does not seem to work

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>

在此处输入图片说明

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM