I’m new to JavaScript, so I’m not sure what keywords to search to find my specific answer. Thanks in advance for your help.
I need to dynamically create li
tags with a href
s in the nav
. These will scroll to 4 different sections in main
.
I have created each li
and a href
.
I now need to get the text from each h2
to the a
element in each li
I have started by creating an array from the h2
elements, but now realized that I could use the outerHTML from the previous array.
How can I get the h2
text, or access the outerHTML property from the sectionIds array?
//creates a element and assigns to listItemHref
const listItemHref = document.createElement('a');
//assigns #nav_list or ul to variable navList
const navList = document.querySelector('#nav_list');
//creates array from id's in section elements
const sectionIds = Array.from(document.getElementsByTagName('section'));
//creates array of h2
const sectionH2 = Array.from(document.getElementsByTagName('h2'));
for (section of sectionIds){
//creates a <li> element for each section name
const listItem = document.createElement('li');
//creates an <a> element for each section name
const listItemHref = document.createElement('a');
//sets the "href" for each <a> element
listItemHref.setAttribute("href", "#" + section.id);
listItem.setAttribute("class", "line_item");
listItem.appendChild(listItemHref);
navList.appendChild(listItem);
}
//code to take h2 text and insert into a tag text
for (heading of sectionH2){
// ? not sure
}
<header class="page_header" id="home">
<h1>Resume</h1>
<!--each li is created using JavaScript-->
<nav class="nav_menu">
<ul id="nav_list">
<li class="line_item">
<a href="#education"></a></li>
<li class="line_item">
<a href="#my_projects"></a></li>
<li class="line_item">
<a href="#about"></a></li>
<li class="line_item">
<a href="#contact"></a></li>
</ul>
</nav>
</header>
<main>
<section id="education">
<h2>My Education</h2>
</section>
<section id="my_projects">
<h2>My Projects</h2>
</section>
<section id="about">
<h2>About Me</h2>
</section>
<section id="contact">
<h2>Contact Me</h2>
</section>
</main>