• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

224
Views
How exactly is a forEach loop working in this scenario?
const navLink = document.querySelectorAll(".nav-link");
navLink.forEach((link) =>
  link.addEventListener("click", () => {
    ul.classList.remove("show");
  })
);

I'm trying to understand the logic behind the forEach in this scenario, I'm new to javascript and programming in general and it's been a challenge to be able to translate what I want into a programing language.

I read different posts regarding forEach syntax but it's truly a lot of technical there and I wasn't able to quite catch their meaning.

about 3 years ago · Juan Pablo Isaza
3 answers
Answer question

0

The forEach function loops over a list of HTML elements or array entries.

In this case, Document#querySelectorAll can return multiple entries, so this allows you to run the same code for each entry.

about 3 years ago · Juan Pablo Isaza Report

0

A forEach kinda does what it says. It loops over each element in the array. In your code all the navLinks are grabbed and stored into const navLink and looped over. After that a click event is added to each of them.

The function inside this click event will remove the show class from ul whenever this click event is triggered. This will be whenever an element with the class nav-link is clicked.

about 3 years ago · Juan Pablo Isaza Report

0

MDN is both beginner friendly and comprehensive when it comes to web development terms/concepts. In your case: Array/forEach.


To answer your question precisely, the forEach function presented will be run once for each element with a class of nav-link found in DOM at the time the script is executed and will add a click event listener to each of those elements.

The event listener (the function bound to run when one of the elements is clicked) consists of an arrow function. That function will attempt to remove the class show from the HTMLElement referenced by a previously declared variable/constant named ul, which is not present in the code you have shown so far.

If ul is not referencing an HTMLElement when .nav-link is clicked, you will see an error in console complaining ul does not have a property called classList.

If ul is present and references an HTMLElement, the function will remove the class show from that element, if the element has that class. Otherwise it will do nothing (without any error/warning).

about 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error