JavaScript中非常基本的setAttribute

Very Basic setAttribute on JavaScript

本文关键字:setAttribute 非常 JavaScript      更新时间:2023-09-26

我是JavaScript的初学者,我不明白为什么在这个简单的代码中,出现在控制台颜色。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时,我创建了一个元素对象,并且可以使用方法: setAttribute。

提前感谢,如果我的问题是愚蠢的,对不起。

document.getElementsByClassName("red")返回一个类似数组对象的dom对象。所以你应该这样写:

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

document.getElementsByClassName返回一个NodeList。您必须使用索引从节点列表中选择一个节点。

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