我是 JavaScript 新手,所以我不确定要搜索哪些关键字才能找到我的具体答案。在此先感谢您的帮助。
我需要li
在a href
. nav
这些将滚动到 4 个不同的部分main
。
我已经创建了每个li
和a href
.
我现在需要通过从元素
创建一个数组来h2
从每个a
元素中获取文本,但现在我意识到我可以使用前一个数组中的 outerHTML。
如何获取文本,或从 sectionIds 数组访问 outerHTML 属性?li
h2
h2
//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>