赋值中的左侧无效:未捕获的ReferenceError:

时间:2018-05-05 04:28:30

标签: javascript

<script>
    document.getElementsByClassName("blue").text-color = "darkblue";
</script>

我认为这是JavaScript初学者的练习部分。我无法找到错误。

<div>
    <span class="blue">This text should be dark blue.</span><br>
</div>

必须采取哪些措施来纠正此错误?

1 个答案:

答案 0 :(得分:2)

getElementsByClassName()返回 HTMLCollection 。您必须指定索引才能获得所需的元素。要设置文本的颜色,您必须在color上设置style属性:

更改document.getElementsByClassName("blue").text-color = "darkblue";

document.getElementsByClassName("blue")[0].style.color = "darkblue";

工作代码示例:

document.getElementsByClassName("blue")[0].style.color = "darkblue";
<div>
    <span class="blue">This text should be dark blue.</span><br>
</div>