Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

105
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!