Home > database >  I want to make a js function which takes every element out of a div and activates a CSS block for it
I want to make a js function which takes every element out of a div and activates a CSS block for it

Time:11-24

I wanted to make this function with flask, but you can apparently only do it with js and I am doing it for the first time. Code:

const navSlide2 = () => {
    const burger = document.querySelector('.burger');
    const nav = document.querySelectorAll('.test');

    burger.addEventListener('click',()=>{
        nav.classList.toggle('heading-nav-active');
    });
}

I want that all the elements with the class "test" are selected and the "heading-nav-active" function in the CSS file should be applied for each selected element. How can I do that?

CodePudding user response:

As @Andy mentioned, queryselectorAll returns a nodelist and you need to iterate it and add/toggle the necessary class. You can do as below

const navSlide2 = () => {
  const burger = document.querySelector('.burger');
  const navs = document.querySelectorAll('.test');

  burger.addEventListener('click', () => {
    navs.forEach(el => el.classList.toggle('heading-nav-active'));
  });
}

Thanks @ChrisG for mentioning the naming convention.

  • Related