getElementsByTagName似乎不起作用 [英] getElementsByTagName does not seem to work

查看:207
本文介绍了getElementsByTagName似乎不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释为什么我的代码不工作!



当我通过Id获取元素时,它工作得很好。但是与getElementsByTagName()相同的方法不会。



另外如果我使用querySelector(),它可以工作。但是如果我使用querySelectorAll(),则返回相同的错误。



test.html:15未捕获TypeError:无法设置未定义的属性color



这是我的代码:

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


解决方案



您可以清楚地看到文档,getElementsByTagName 返回一个元素数组,而不是单个元素。 p>

所以你必须遵循正确的索引,否则会抛出一个例外,就像你的情况一样。


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.

这篇关于getElementsByTagName似乎不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆