我正在使用 querySelector()
来更改类中的某些样式:
el.querySelector('.fa fa-car').style.display = "none";
这适用于一个元素,但如果有更多元素包含此类,并且我想将所有元素的显示更改为无,则此命令只会删除第一次出现的元素,而不会影响下一个元素。
我试着用 querySelectorAll()
来做到这一点:
el.querySelectorAll('.fa fa-car').style.display = "none";
但是这个返回错误信息:
html2canvas: TypeError: Cannot set property 'display' of undefined
关于如何获取包含特定类的所有元素并对它们执行操作的任何想法?
最佳答案
The Element method
querySelectorAll()
returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.
使用Document.querySelectorAll()
获取所有元素。然后使用forEach()
在每个元素中设置样式:
var elList = document.querySelectorAll('.fa.fa-car');
elList.forEach(el => el.style.display = "none");
请注意:一些旧版本的 IE (<8) 将不支持 querySelectorAll()
。在那种情况下使用
Array.from(document.querySelectorAll('.fa.fa-car'))
关于javascript - 使用 querySelector 获取包含类的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52365938/