skip to Main Content

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


  1. Pass a single selector string that includes commas, instead of multiple arguments.

    const els = document.querySelectorAll('.icon-bar.bar-top, .icon-bar-bar-middle, .icon.bar-bottom');
    

    To get all the matching elements rather than only the first, use document.querySelectorAll instead of document.querySelector.

    Then, you will need to loop over the elements of the NodeList to manipulate each one.

    els.forEach(el => el.classList.add('hero-icon-bar-scroll'));
    
    Login or Signup to reply.
  2. You can use querySelectorAll to select multiple elements by using multiple selectors separated by commas like this:

    const heroIconBarScroll = document.querySelectorAll('.icon-bar.bar-top, .icon-bar-bar-middle, .icon.bar-bottom');
    
    // inside the scroll event handler
    heroIconBarScroll.forEach(el => {
      // apply what you want to apply to all elements
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search