Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/457.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 无法在JS中使用style方法_Javascript_Css_Html - Fatal编程技术网

Javascript 无法在JS中使用style方法

Javascript 无法在JS中使用style方法,javascript,css,html,Javascript,Css,Html,在此代码中: <header class="alg">Some text</header> <script> var header = document.getElementsByClassName("alg"); header.style.color = 'red'; </script> 一些文本 var header=document.getElementsByClassName(“alg”); header.style.color='red

在此代码中:

<header class="alg">Some text</header>
<script>
var header = document.getElementsByClassName("alg");
header.style.color = 'red';
</script>
一些文本
var header=document.getElementsByClassName(“alg”);
header.style.color='red';
在运行它之后。我从日志中得到:

TypeError:header\u m.style未定义

我做错了什么?

返回多个元素

因此,您访问它的方式不正确。在这种情况下,您想要的是:

 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.

返回多个元素

因此,您访问它的方式不正确。在这种情况下,您想要的是:

 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.

太好了!谢谢。@edem不用担心,伙计!很高兴能帮上忙那太好了!谢谢。@edem不用担心,伙计!很乐意帮忙