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

181
Views
Using forEach method with Array to build navigation menu and unordered list with JS

I am trying to generate an unordered list and also navigation bar using JavaScript.

This is the JS snippet I have (looping through an Array using a forEach method):

const navMenu = document.querySelectorAll("page_header");
const navList = document.getElementById("menu_list");
const items = Array.from(document.querySelectorAll("section"));
items.forEach((item, i) => {

    const listItem = document.createElement("li");
    listItem.classList.add("menu-item");
    const anchorTag = document.createElement("a");
    anchorTag.innerText = item;
    const sectionName = item.getAttribute('data-nav');
    const sectionID = item.getAttribute('id');
    listItem.innerHTML = createNavItemHTML(sectionID, sectionName);
    navList.appendChild(listItem);

});

I also want to rewrite this function somehow since I took it straight off from a github repo that I am not comfy taking straight off.

 function createNavItemHTML(id, name) {
        const itemHTML = `<a class ="menu__link" data-id="${id}">${name}</a>`;
        return itemHTML;
    }

I simply want to include an anchor tag in my unordered list for each list item. But cannot get it to work...

Thanks in advance.

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

0

You can simplify your code alot:

const navList = document.getElementById("menu_list");
const sections = document.querySelectorAll("section");
for (const section of sections) {
    const li = document.createElement("li");
    li.className = "menu-item";
    const a = document.createElement("a");
    a.textContent = section.dataset.nav;
    a.href = `#${section.id}`;
    li.appendChild(a);
    navList.appendChild(li);
};

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!