madsjorg madsjorg - 3 months ago 8
jQuery Question

Target all the specific elements except the on clicked on

Inside the loop in the function

thirdNavFunction
, I need to target all the
.third-nav
classes except the one clicked on and it needs to be done without jQuery, how do I do this?

var thirdNav = document.getElementsByClassName("third-nav");


for (var i = 0; i < thirdNav.length; i++){
thirdNav[i].addEventListener("click", thirdNavFuntion);
}

function thirdNavFuntion() {

for (i = 0; i < thirdNav.length; i++) {
thirdNav[i].parentElement.className = "";
}

if (this.parentElement.className === "") {
this.parentElement.className = "nav-sub-li-active";
} else {
this.parentElement.className = "";
}
}


In the code here, I target all the
.third-nav
divs, but that doesn't work as intended, I need to exclude the one that is clicked. I hope it makes sense.

Answer
  • Convert thirdNav to array using Array.from().
  • Filter out the clicked element using the filter() method.
  • Call the forEach method to change the class name of all parent elements.
function thirdNavFuntion() {
  const elements = Array.from(thirdNav).filter(el => el !== this)
  elements.forEach(el => el.parentElement.className = "")
}
Comments