繁体   English   中英

querySelectorAll.style不起作用

[英]querySelectorAll.style does not work

我正在用JavaScript编写一些我需要使用querySelectorAll.style东西,但是它总是返回undefined,但是它可以与querySelector.style完美配合。 如何使其正常工作,以便设置样式?

document.querySelector("div#tabs" + tabId + "> div.page").style.display = 'none'; //works
document.querySelectorAll("div#tabs" + tabId + "> div.page").style.display = 'none';// doesn't work 

querySelector

返回文档中的第一个元素...

querySelectorAll

返回文档中元素的列表。

在第一个IE中,您要对单个元素进行操作,该元素确实具有style属性。 第二个是元素列表,因此您需要使用样式遍历该列表:

var els = document.querySelectorAll("div#tabs" + tabId + "> div.page");
for (var x = 0; x < els.length; x++)
    els[x].style.display = 'none';

querySelectorAll返回元素列表,而不是单个元素列表。

因此,这应该可以将样式应用于找到的第一个元素:

document.querySelectorAll("div#tabs" + tabId + "> div.page")[0].style.display = 'none'; // First element

querySelectorAll返回元素的html集合,而不是单个元素,因此您需要遍历结果:

Array.from(document.querySelectorAll("div#tabs" + tabId + "> div.page"))
    .forEach(function(val) {
        val.style.display = 'none';
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM