javascript - "Cannot set color of undefined"是什么意思?

标签 javascript html css

<分区>

我使用以下功能将我的“时钟网站”更改为更轻的主题。

var light = function() {
    document.getElementsByClassName('themechange').style.color = "black"
    document.getElementsByTagName('body').style.backgroundColor = "white";
};

当我尝试运行函数时,标题中出现错误。如果您需要更多代码,请检查元素 here

最佳答案

两者都是Document.getElementsByClassName()Document.getElementsByTagName()返回 NodeLists对象。

您不能将设置直接应用于 NodeList ,您必须遍历它并将设置应用于每个 Node .

但是您可以使用 Document.body直接引用 body 元素。

Document.getElementsByClassName()not supported in Internet Explorer 8但是Document.querySelectorAll()supported .

/*    Select all elements with the class `themechange`
 *    Iterate with a for loop
 *    Set each element's background color to `black`
 *    Set the body's background color to `white`
 */
var light = function() {
    var themeChanges = document.querySelectorAll('.themechange'), themeChange, i;
    for(i = 0; (themeChange = themeChanges[i]); i++) {
        themeChange.style.color = "black"
    }
    document.body.style.backgroundColor = "white";
};

关于javascript - "Cannot set color of undefined"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30657376/

上一篇:javascript - 鼠标悬停时交换图像

下一篇:html - 白色框出现在我的导航栏顶部

相关文章:

javascript - Angularjs ng重复错误

javascript - 如何获取跨域iframe内容的html,或者如何通过其他方式获取另一个域的html?

android - CSS 引用手机的表情符号字体?

javascript - Safari 10 中的新输入占位符行为 - 不再通过 JavaScript 隐藏更改

CSS - 无法获取样式属性

html - 我是否应该使用 CSS 过滤器,因为它处于工作草案状态

javascript - JSON 请求的无效标签错误

javascript - 无需提交表单或输入 ReactJs 即可获取选项值

javascript - 让 Parsley.js 识别未隐藏​​的表单元素

javascript - 当我们使用 jquery 将 div 悬停时如何使 Class 保持不变