JavaScript 上的非常基本的 setAttribute

Very Basic setAttribute on JavaScript

我是 JavaScript 的初学者,我不明白为什么在这个简单的代码中,出现在控制台中的 color.setAttribute 不是一个函数

<style>
 .red {color:red;}
 .blue { color: blue;}
</style>
</head>
<body>
<p class="red">Hello World</p>
<script>
 var color = document.getElementsByClassName("red");
 color.setAttribute("class","blue");
</script>
据我所知,在声明变量 color 时,我创建了一个 元素对象 并且我可以使用 方法 : 设置属性。

在此先致谢,如果我的问题很愚蠢,我深表歉意。

document.getElementsByClassNamereturns一个NodeList。您必须使用索引 select 节点列表中的一个节点。

var color = document.getElementsByClassName("red")[0]; // the first element

document.getElementsByClassName("red") returns 一个 dom 对象,它是类似数组的对象。所以你应该这样写。

var color=document.getElementsByClassName("red")[0];
color.setAttribute("class","blue");