Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

querySelectorAll.style does not 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 
like image 969
Computer Backup Avatar asked Oct 12 '15 16:10

Computer Backup


People also ask

Why is my querySelectorAll not working?

The "querySelectorAll is not a function" error occurs for multiple reasons: calling the method on an object that is not a valid DOM element or the document object. placing the JS script tag above the code that declares the DOM elements. misspelling the querySelectorAll method (it's case sensitive).

What does the querySelectorAll () method do?

Document.querySelectorAll() The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.

What is the difference between querySelectorAll and querySelector?

The difference between these two is that querySelector returns a single element matching its selection criteria. querySelectorAll, on the other hand, returns all elements matching the search criteria in an iterable list.


2 Answers

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';
like image 180
James Thorpe Avatar answered Oct 29 '22 10:10

James Thorpe


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
like image 22
Richard Dalton Avatar answered Oct 29 '22 10:10

Richard Dalton