0

i'm very new to JS so be nice haha, but i'm trying to create a table of contents on a page using the DOM.

const h2 = document.querySelectorAll('h2');
const toc = document.querySelector('#toc')
h2.forEach(heading => {
 toc.innerHTML = `<li><a href="">${heading}</a></li>`
})

it's not working how i would expect tbh. any help is appreaciated, i'm probably just being dumb

asked Aug 21, 2021 at 21:18
2
  • 4
    "it's not working how i would expect tbh" — Tell us what it is doing, not just what it isn't. Tell us what you expect, don't make us guess. Commented Aug 21, 2021 at 21:19
  • ah sorry, i expect it to go through the h2's, print them each out as an <li> on the DOM Commented Aug 21, 2021 at 21:21

2 Answers 2

4

I think something like this should work! Here's what I changed to get it to work:

  • Use += instead of = for innerHTML. If you just use =, every time the forEach runs, it replaces the content. You're trying to create a list, so you want it to add on.
  • Get the innerText from heading. heading is an element, so you have to go into it and get its text, or else what you display isn't going to look right.

const h2 = document.querySelectorAll('h2');
const toc = document.querySelector('#toc')
h2.forEach(heading => {
 toc.innerHTML += `<li><a href="">${heading.innerText}</a></li>`
})
<ul id="toc"></ul>
<h2>One</h2>
<h2>Two</h2>

Spectric
32.6k6 gold badges32 silver badges56 bronze badges
answered Aug 21, 2021 at 21:21
Sign up to request clarification or add additional context in comments.

1 Comment

A word of caution: innerHTML is usually a bad practice and also not good for performance. stackoverflow.com/questions/11515383/…
1

Regarding @Utkarsh Dixit comment: This is much more performant and is creating the same result.

const h2 = document.querySelectorAll('h2');
const toc = document.querySelector('#toc')
h2.forEach(heading => {
 // Create two elements
 const li = document.createElement('li')
 const anchor = document.createElement('a')
 // Assign the text content to the anchor
 anchor.textContent = heading.textContent
 // Add them together toc > li > anchor
 li.append(anchor)
 toc.append(li)
})
<ul id="toc"></ul>
<h2>One</h2>
<h2>Two</h2>

answered Aug 21, 2021 at 22:43

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.