关于JavaScript的非常基本的setAttribute

Reb*_*ers 2 javascript element object setattribute

我是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>
Run Code Online (Sandbox Code Playgroud)
据我所知,当声明变量颜色时,我创建了一个元素对象,我可以使用方法:setAttribute.

在此先感谢,如果我的问题很愚蠢,那就很抱歉.

Akh*_*mar 8

document.getElementsByClassName("red")返回一个像对象一样的dom对象.所以你应该写下面的内容.

var color=document.getElementsByClassName("red")[0];
color.setAttribute("class","blue");
Run Code Online (Sandbox Code Playgroud)

  • 从技术上讲,它不会返回一个数组,而是一个[HTMLCollection](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection),它是一个类似数组的对象,它有一个`.length`属性就像一个数组,支持`[i]`像数组一样索引,但没有任何常用的数组方法,如`.forEach()`或`.slice()`. (2认同)