Home > Software engineering >  Using forEach method with Array to build navigation menu and unordered list with JS
Using forEach method with Array to build navigation menu and unordered list with JS

Time:11-11

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.

CodePudding user response:

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);
};
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related