Javascript 使用类名更改属性
我想使用以下方法更改属性:Javascript 使用类名更改属性,javascript,css,attributes,Javascript,Css,Attributes,我想使用以下方法更改属性: document.getElementsByClassName('a').setAttribute("color","red") 但这在Chrome中不起作用。控制台告诉我 setAttribute不是一个函数 你能告诉我使用什么javascript函数吗?谢谢。返回类似数组的对象,而不是单个元素。您需要访问索引项。同时设置attibute样式,而不是颜色。如果有多个元素,可以使用循环在类似数组的对象上迭代并设置属性 document.getElementsByCl
document.getElementsByClassName('a').setAttribute("color","red")
但这在Chrome中不起作用。控制台告诉我
setAttribute不是一个函数
你能告诉我使用什么javascript函数吗?谢谢。返回类似数组的对象,而不是单个元素。您需要访问索引项。同时设置attibute样式
,而不是颜色
。如果有多个元素,可以使用循环在类似数组的对象上迭代并设置属性
document.getElementsByClassName('a')[0].setAttribute("style","color:red")
------------------------------------^^^----------------------------
代码示例
document.getElementsByClassName('a')[0].setAttribute(“样式”,“颜色:红色”)代码>
测试1
测试2退出
您可以像这样尝试document.getElementsByClassName('.a').style.color=“red”代码>
我想这是您想要的。这将帮助您找到问题的答案。如果我想用“a”类更改所有元素的颜色,我该怎么办?请参阅我答案的下面部分