javascript querySelectorAll.style 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33085889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
querySelectorAll.style does not work
提问by Computer Backup
I am writing something in JavaScript that I need to use querySelectorAll.style
but it always returns undefined, but it works perfectly with querySelector.style
. How can I make it work properly so I can set the style?
我正在用 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
回答by James Thorpe
Returns the first element within the document...
返回文档中的第一个元素...
Returns a list of the elements within the document...
返回文档中元素的列表...
IE in the first one, you're operating on a single element, which does have a style
property. The second one is a list of elements, so you need to loop over that list applying the style:
在第一个 IE 中,您操作的是单个元素,该元素确实具有style
属性。第二个是元素列表,因此您需要应用样式遍历该列表:
var els = document.querySelectorAll("div#tabs" + tabId + "> div.page");
for (var x = 0; x < els.length; x++)
els[x].style.display = 'none';
回答by Richard Dalton
querySelectorAllreturns a list of elements rather than a single one.
querySelectorAll返回元素列表而不是单个元素。
So this should work to apply the style to the first element found:
所以这应该可以将样式应用于找到的第一个元素:
document.querySelectorAll("div#tabs" + tabId + "> div.page")[0].style.display = 'none'; // First element
回答by baao
querySelectorAll returns a html collection of elements, not a single element, so you need to loop over the results:
querySelectorAll 返回元素的 html 集合,而不是单个元素,因此您需要遍历结果:
Array.from(document.querySelectorAll("div#tabs" + tabId + "> div.page"))
.forEach(function(val) {
val.style.display = 'none';
});