Skip to content
Advertisement

How to carete dynamic NavBar with only JavaScript

I have this code right now, but its not working on the DOM, I am wondering what is the problem with my code. My current code:

“JavaScript”

const sectionElements = document.querySelectorAll('section');
const menuList = document.getElementById('navbar__list');

function NavBarCreate (){
    for (let i = 0; i < sectionElements.length; i++){
        const listStart = document.createElement('li');
        const attributeId = sectionElements[i].getAttribute('id');
        const attributeName = sectionElements[i].getAttribute('data-nav');
        listStart.innerHTML = 
        `<a href="${attributeId}" class="menu__link">${attributeName}</a>`;
        menuList.appendChild(listStart);   
    }
}

“HTML”

<nav class="navbar__menu">
   <ul id="navbar__list"></ul>
</nav>
<main>
<section  id="section1" data-nav="Section 1">
</section>

<section  id="section2" data-nav="Section 2">
</section>
</main>

<

Advertisement

Answer

call the function or avoid the function. try it

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement