AGS
AGS

Reputation: 53

EDIT: Selecting Multiple Classes then toggle classes for each of them

I found a way to make this work but I am thinking if there is a better way. I am trying to make changes to the divs via classes only.

I am trying to toggle 4 class with 1 click.

I grab the class for the button then add click "add event listener", withing the function i grab all 4 classes using querySelector all and assign to a variable called slide.

 const slide = document.querySelectorAll( 
'.header__btn, .wrap__content, .content__aside, .nav'
);

I know that querySelector grabs them in order by reading HTML from top to bottom. I am only selecting the elements that will never change.

I want to toggle a class list for each of the elements, what is the best way???

I am using:

slide[0].classList.toggle('header__btn--animate');
slide[1].classList.toggle('wrap__content--slide');
slide[2].classList.toggle('content__aside--slide');
slide[3].classList.toggle('nav--slide');

They toggle classes at the same time which is fine, i want them to do that.

Is there a better way of doing this.

Thanks

Upvotes: 1

Views: 43

Answers (1)

Ori Drori
Ori Drori

Reputation: 191976

Move the classes to an array of [class to find, class to toggle] . Iterate the array with Array.forEach(). Get all items for this class using document.querySelectorAll(). Iterate the items with NodeList.forEach(), and for each item toggle its respective class.

const classes = [['.header__btn', 'header__btn--animate'], ['.wrap__content', 'wrap__content--slide'], ['.content__aside', 'content__aside--slide'], ['.nav', 'nav--slide']]

btn.addEventListener('click', () => {
  classes.forEach(([cls, clsToggle]) => 
    document.querySelectorAll(cls)
      .forEach(el => el.classList.toggle(clsToggle))
  )
})

Upvotes: 1

Related Questions