简体   繁体   中英

how i can use toggle and function that remove the class from the previous element together only using JavaScript i have tried to Different ways?

- First Way -

Here I Can't Remove The Previous Elements and add the class for The new One

linksBtnArr.forEach((item, index) => {
  item.addEventListener("click", () => {
    arrowArr[index].classList.toggle("active");
    if (arrowArr[index].classList.contains("active")) {
      menuArr[index].style.display = "block";
    } else {
      menuArr[index].style.display = "none";
    }
  });
}); 

- Second Way -

Here I Can remove The previous Element But i Can't use Toggle to Remove The class Form The Same Element That i clicked again

linksBtnArr.forEach((link, i) => {
  link.addEventListener("click", () => {
    removeActiveClasses();
    arrowArr[i].classList.add("active");
  });
});
// Remove The previous Menu
function removeActiveClasses() {
  arrowArr.forEach((arrow) => {
    arrow.classList.remove("active");
  });
}

this way

linksBtnArr.forEach( (lk,_,All_lk) => {
  lk.onclick =_=> {
    if (lk.classList.toggle('active'))
      All_lk.forEach( lx=> lx.classList.toggle('active', lk===lx) )
  } })

Look At The UL Links That what i'm trying to Do ! https://mohmostafa-web.github.io/blogr-landing-page-frontend-mentor

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM