通过Javacript更改类样式

时间:2019-04-18 12:31:32

标签: styles

我在页面顶部使用了style标签,该标签使用“ class”属性定义了正文中元素使用的样式。 示例:

.itemColor { color:red; }

是否可以使用JavaScript在标记color中定义的类中更改style属性的值?

备注:我是编码的初学者!...

1 个答案:

答案 0 :(得分:0)

在您的示例中,您将首先选择您的商品,然后更改其样式:

    myitem = document.getElementById("itemColor") // searches in all children and grandhildren of document
    myitem.style.color = "blue";

您可以对getElementsByClassNamegetElementsByTagName中的元素(它们是HTML集合)执行相同的操作。

通过以下内容,您可以覆盖具有所述类的所有元素的属性。

myitems = document.getElementsByClassName("itemColor")  // HTMLCollection
[].forEach.call(myitems, function(subitem){
        subitem.style.color = "blue";
    }
);

console.log(myitem.style)以查看可以更改的所有属性。

相关问题