Home > database >  Problem with JS add and remove class for elements
Problem with JS add and remove class for elements

Time:09-01

I have a code that adds or removes a class from elements. But it does this only for the menu, but not for the content (a huge white square in the middle), although it should for both at the same time. I need that when clicking on any button in the menu, the 'is-active' class changes both in the menu and in the content.

without clicking on the menu.png

with a click on the menu.png

  const list = Array.from(document.querySelectorAll('.list'))
  const play = Array.from(document.querySelectorAll('.play'))

  const clearActiveClass = (element, className = 'is-active') => {
    element.find(item => item.classList.remove(`${ className }`))
  }

  const setActiveClass = (element, index, className = 'is-active') => {
    element[index].classList.add(`${ className }`)
  }

  const checkoutTabs = (item, index) => {
    item.addEventListener('click', () => {

      if (item.classList.contains('is-active')) return
      console.log(item)

      clearActiveClass(list)
      clearActiveClass(play)

      setActiveClass(list, index)
      setActiveClass(play, index)
    })
  }

  list.forEach(checkoutTabs)

CodePudding user response:

The inner function to find needs to be something that finds an element containing className. Once you have found the element, you can remove the className class.

  const clearActiveClass = (element, className = 'is-active') => {
    element.find(item => item.classList.contains(className)).classList.remove(className);
  }
  • Related