gpt4 book ai didi

javascript - JavaScript 上非常基本的 setAttribute

转载 作者:行者123 更新时间:2023-12-01 16:15:50 25 4
gpt4 key购买 nike

我是 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 时,我创建了一个 元素对象,我可以使用 方法:setAttribute.

提前致谢,如果我的问题太愚蠢,我深表歉意。

最佳答案

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

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

关于javascript - JavaScript 上非常基本的 setAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30554070/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com