getElementsByTagName获取的数组 forEach报错

338 阅读1分钟

在vue中想要通过类名获取元素修改样式,获取元素后forEach却报错

  let [isactive, inactive] = [
        document.getElementsByClassName("active"),
        document.getElementsByClassName("inactive"),
      ];
      isactive.forEach((item) => {
        item.style.color = this.activeColor;
      });
      inactive.forEach((item) => {
        item.style.color = this.inactiveColor;
      });

为什么会报错?

document.getElementsByClassName返回一个数组-类似于Object而不是实际的数组 由于类数组对象继承自'Object.prototype'而不是'Array.prototype',因此这意味着类数组对象无法访问常见的Array原型方法,例如forEach(),push(),map(), filter()和slice()。

let isactive = document.getElementsByClassName("active"), 
conslog(typeof isactive) //object

解决方法(通过Array.prototype.slice将其变为数组)Array.prototype.slice

  let isactiveList = Array.prototype.slice.call(isactive);
      isactiveList.forEach((item) => {
          item.style.color = this.activeColor;
      });