我是 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>
提前致谢,如果我的问题太愚蠢,我深表歉意。
最佳答案
document.getElementsByClassName("red")
返回一个类似数组的 dom 对象。所以你应该写以下内容。
var color=document.getElementsByClassName("red")[0];
color.setAttribute("class","blue");
关于javascript - JavaScript 上非常基本的 setAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30554070/