¿Cómo genero una tabla de contenido dinámicamente? El siguiente es mi código, pero es solo para una etiqueta de encabezado h3. Necesito que funcione para todos los títulos. Aquí está mi siguiente formato de muestra de la publicación:
<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>¿Cómo genero una tabla de contenido dinámicamente? El siguiente es mi código, pero es solo para una etiqueta de encabezado h3. Necesito que funcione para todos los títulos.
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); }); } });