最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - querySelectorAll.style does not work - Stack Overflow

programmeradmin3浏览0评论

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?

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

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?

document.querySelector("div#tabs" + tabId + "> div.page").style.display = 'none'; //works
document.querySelectorAll("div#tabs" + tabId + "> div.page").style.display = 'none';// doesn't work 
Share Improve this question edited Oct 12, 2015 at 16:28 Musa 97.7k17 gold badges122 silver badges142 bronze badges asked Oct 12, 2015 at 16:26 Computer BackupComputer Backup 1871 gold badge4 silver badges14 bronze badges 0
Add a comment  | 

3 Answers 3

Reset to default 8

querySelector:

Returns the first element within the document...

querySelectorAll:

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:

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

querySelectorAll returns a list of elements rather than a single one.

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

querySelectorAll returns a html collection of elements, not a single element, so you need to loop over the results:

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

评论列表(0)

  1. 暂无评论