如何使 .querySelectorAll() 或 .forEach() 在 Firefox 中工作? [英] How can I make .querySelectorAll() or .forEach() work in Firefox?

查看:16
本文介绍了如何使 .querySelectorAll() 或 .forEach() 在 Firefox 中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想删除所有具有 sample 类的元素.

I want to remove all elements with class sample.

这在 Chrome 和 Safari 中运行良好:

This is working well in Chrome and Safari:

document.querySelectorAll('.sample').forEach(function(e) {
    e.parentNode.removeChild(e);
});

这是我在 Firefox 中遇到的错误:

Here is the error I get in Firefox:

TypeError: document.querySelectorAll(...).forEach 不是函数

TypeError: document.querySelectorAll(...).forEach is not a function

推荐答案

document.querySelectorAll 返回一个 NodeList,它像数组一样索引,但不是数组,所以你不能调用数组方法就可以了.

document.querySelectorAll returns a NodeList which is indexed like an array, but not an Array so you can't call the array methods on it.

您可以在 ES6 中使用 Array.from(nodeList) 或在 ES5 中使用 Array.prototype.slice.call(nodeList)

You can use Array.from(nodeList) in ES6 or Array.prototype.slice.call(nodeList) for ES5

 Array.from(document.querySelectorAll('selector')).forEach(el => el)

这篇关于如何使 .querySelectorAll() 或 .forEach() 在 Firefox 中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆