madsjorg madsjorg - 1 year ago 57
jQuery Question

Target all the specific elements except the on clicked on

Inside the loop in the function

, I need to target all the
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
divs, but that doesn't work as intended, I need to exclude the one that is clicked. I hope it makes sense.

Answer Source
  • 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 = "")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download