0

このコードでは:

<header class="alg">Some text</header>
<script>
var header = document.getElementsByClassName("alg");
header.style.color = 'red';
</script>

実行した後。ログから取得しました:

TypeError: header_m.style is undefined

私は何を間違っていますか?

4

1 に答える 1

4

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.

jsFiddle.

于 2013-06-02T23:03:25.600 に答える