Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

121
Visualizações
javascript foreach with DOM

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

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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>

about 4 years ago · Juan Pablo Isaza Relatório

0

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>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda