在这段代码中:
<header class="alg">Some text</header>
<script>
var header = document.getElementsByClassName("alg");
header.style.color = 'red';
</script>
运行后。我从日志中得到:
TypeError: header_m.style is undefined
我做错了什么?
在这段代码中:
<header class="alg">Some text</header>
<script>
var header = document.getElementsByClassName("alg");
header.style.color = 'red';
</script>
运行后。我从日志中得到:
TypeError: header_m.style is undefined
我做错了什么?
getElementsByClassName
返回多个元素。
因此,您正在不正确地访问它。在这种情况下,您想要的是:
header[0].style.color = 'red';
// ^ [0] will get the first element with the class,
// which is in this case your is header element. [1] would get the second, etc.