Alexander Georgiev Alexander Georgiev - 3 months ago 13
jQuery Question

jQuery: How to add automatically LI elements from each heading in article

I would like to implement the "ScrollSpy" (I use Materialize) in each blog post. The best implementation I think is with jQuery. However, I am struggling to make it dynamic. So, far I have this code.

$('body.single .entry-content').append('<div class="col hide-on-small-only m3 l2"><ul class="section table-of-contents"></ul></div>');

var h2 = $('.entry-content').find('h2').text();
var h3 = $('.entry-content').find('h3').text();

$('ul.table-of-contents').append("<li><a href='#" +h2 +"'>" +h2 +"</a></li>");
$('ul.table-of-contents').append("<li><a href='#" +h3 +"'>" +h3 +"</a></li>");


How can I make it dynamic based on number of h2, h3, h4, etc. ?

Answer

You can loop through the header elements and then add the li elements like:

var html = '';
$('.entry-content').find('h2, h3, h4, h5').each(function() {
  var header = $(this).text();
  html += "<li><a href='#" + header + "'>" + header + "</a></li>";
});
$('ul.table-of-contents').append(html);
Comments