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

107
Visualizações
Generate Table of content dynamicaly with jquery

How do I generate table of contents dynamically. following is my code but its only for one heading tag h3. I need it to work for all headings. Here is my following sample format of the post :

<html>
<head></head>
<body>


<div id="tableofcontent"></div>
<div class="entry-content">
<h1 id="Test1">Main Heading</h1>
<p>Lorem Ipsum Lorem IpsumLorem IpsumLorem Ipsum</p>
<h2 id="Test2"> Sub Heading</h2>
<p>Lorem Ipsum Lorem IpsumLorem IpsumLorem Ipsum</p>
  <h3 id ="Test3">Sub Sub Heading</h3>
    <p>Lorem Ipsum Lorem IpsumLorem IpsumLorem Ipsum</p>
    <h4>Sub Sub Heading</h4>
    <p>Lorem Ipsum Lorem IpsumLorem IpsumLorem Ipsum</p>
   </div>
   </body> 
</html>

How do I generate table of contents dynamically. following is my code but its only for one heading tag h3. I need it to work for all headings.

jQuery(document).ready(function($) {
  var $aWithId = $('.entry-content h3[id]');
  if ($aWithId.length != 0) {
    if ($aWithId.length > 0) {
      $('#tableofcontent').prepend('<nav class="toc"><h3 class="widget-title">Table of Contents</h3><ol></ol></nav>');
    }

  }
   

var $aWithId = $('.entry-content h3[id]');
if ($aWithId.length != 0) {

  $('.entry-content').find($aWithId).each(function() {
    var $item = $(this);
    var $id = $(this).attr('id');
    var li = $('<li/>');
    var a = $('<a/>', {
      text: $item.text(),
      href: '#' + $id,
      title: $item.text()
    });
    a.appendTo(li);
    $('#tableofcontent .toc ol').append(li);
  });
}
});

about 4 years ago · Juan Pablo Isaza
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