简体   繁体   中英

I can't create a dynamic navigation menu using pure JavaScript

I tried to create a dynamic navigational menu using pure JavaScript but the code doesn't work.

I created an empty unordered list that will be filled automatically using JavaScript

 // Identify container, sections and empty unorder list. const menu = document.getElementById("menu"); const sections = [...document.querySelectorAll("section")] const nav_menu_items = () => { let nav_menu_container = ''; sections.foreach(section => { const sectionID = section.id; const sectionAtrribute = section.dataset.nav; nav_menu_container += `<li> <a class="menu_item_link" href="#${sectionID}">${sectionAtrribut}</a></li>` }) menu.innerHTML = nav_menu_container; } nav_menu_items();
 <body> <header> <nav> <ul id="menu"></ul> </nav> </header> <section id="container" class="container" data-section="big"> <div id="section1" class="section" data-nav="section1">This is section 1 so hello</div> <div id="section2" class="section" data-nav="section2">This is section 2 so hello</div> <div id="section3" class="section" data-nav="section3">This is section 3 so hello</div> <div id="section4" class="section" data-nav="section4">This is section 4 so hello</div> </section> </body>

Corrected three things here:-

  • [...document.querySelectorAll("section")] should be [...document.querySelectorAll(".section")] because section is a class and you need to prefix a class with . when passing in querySelector/querySelectorAll .

  • It's forEach and not foreach .

  • sectionAtrribut should be sectionAtrribute

 <body> <header> <nav> <ul id="menu"></ul> </nav> </header> <section id="container" class="container" data-section="big"> <div id="section1" class="section" data-nav="section1">This is section 1 so hello</div> <div id="section2" class="section" data-nav="section2">This is section 2 so hello</div> <div id="section3" class="section" data-nav="section3">This is section 3 so hello</div> <div id="section4" class="section" data-nav="section4">This is section 4 so hello</div> </section> <script> // Identify container, sections and empty unorder list. const menu = document.getElementById("menu"); const sections = [...document.querySelectorAll(".section")] const nav_menu_items = () => { let nav_menu_container = ''; sections.forEach(section => { const sectionID = section.id; const sectionAtrribute = section.dataset.nav; nav_menu_container += `<li> <a class="menu_item_link" href="#${sectionID}">${sectionAtrribute}</a></li>` }) menu.innerHTML=nav_menu_container; } nav_menu_items(); </script> </body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM