Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

239
Views
What function should I use to loop through Node List in JavaScript?
const navLinks = document.querySelectorAll(".nav-link");
  navLinks.forEach((link) => {
    link.addEventListener("click", (e) => {
      console.log(e.target.classList);
      return e.target.classList.toggle("active");
    });
  });

When I log out the classlist I get a list of all elements with the navLink class, not the clicked one. I have a feeling it's the for each function I am using. How do I get the correct classist as in for the clicked link? , right now when I log out I get classes in all the navlink elements

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

  1. Use stopPropagation to prevent further propagation of events

  2. classList is ArrayLike object, not actually an array. But it can be converted to Array.

const navLinks = document.querySelectorAll(".nav-link");
navLinks.forEach((link) => {
  link.addEventListener("click", (e) => {
    e.stopPropagation(); // prevents further propagation of the current event in the capturing and bubbling phases
    console.log('Array: ', Array.from(e.target.classList));
    console.log('ArrayLike: ', e.target.classList);
    return e.target.classList.toggle("active");
  });
});
.nav-link {
 width: 150px;
 height: 50px;
 border: 1px solid gray;
}
<div class="nav-link 1-item"></div>
<div class="nav-link 2-item"></div>
<div class="nav-link 3-item"></div>
<div class="nav-link 4-item"></div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!