简体   繁体   English

getElementsByTagName似乎不起作用

[英]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. 当我得到By ID元素时,它可以很好地工作。 But the same method with getElementsByTagName() does not. 但是与getElementsByTagName()相同的方法却没有。

Also if I use querySelector(), it works. 另外,如果我使用querySelector(),它也可以工作。 However if I use querySelectorAll() the same error returns. 但是,如果我使用querySelectorAll(),则会返回相同的错误。

test.html:15 Uncaught TypeError: Cannot set property 'color' of undefined test.html:15未捕获的TypeError:无法设置未定义的属性'color'

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. 您可以清楚地看到document,getElementsByTagName返回一个元素数组,而不是单个元素。

So you have to follow proper indexing otherwise it will throw an exception as in your case. 因此,您必须遵循正确的索引编制,否则将像您的情况一样引发异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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