I have created a nav and header section which both change color (along with the hero text) as the user scrolls down the page, link to fiddle below:
https://jsfiddle.net/mfen723/9swhejo5/35/
I need to select all three of the icon bars that I’m using using for the navbar toggler so they also change color along with the nav, hero background and text, but I can’t seem to select all 3 icon bars.
I am currently using the function below but I understand that using document.querySelector selects only the first matching element
const heroIconBarScroll = document.querySelector('.icon-bar.bar-top', '.icon-bar-bar-middle', '.icon.bar-bottom');
window.addEventListener('scroll', () => {
if (window.scrollY >= 46) {
heroIconBarScroll.classList.add('hero-icon-bar-scroll');
} else if (window.scrollY < 56)
heroIconBarScroll.classList.remove('hero-icon-bar-scroll');
});
I have tried using document.querySelectorAll but this seems not to select any of the icon bars.
Any advice appreciated.
2
Answers
Pass a single selector string that includes commas, instead of multiple arguments.
To get all the matching elements rather than only the first, use
document.querySelectorAll
instead ofdocument.querySelector
.Then, you will need to loop over the elements of the
NodeList
to manipulate each one.You can use
querySelectorAll
to select multiple elements by using multiple selectors separated by commas like this: