Skip to content Skip to sidebar Skip to footer

Jquery Automatic Heading Numbering

I have articles on website with 10-15 H2 tag subtitles. Something likes that.

Name of article

Subtitle

.....

Solution 1:

You can numerate backwards by using the each function.

allItems = $("h2").length;
$("h2").each(function (index){
  $(this).prepend(allItems - index + ". ");
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><h1>Name of article</h1><h2>Subtitle</h2><p>.....</p><h2>Subtitle</h2><p>.....</p><h2>Subtitle</h2><p>.....</p><h2>Subtitle</h2><p>.....</p>

Solution 2:

This should help

var h2Elements = $('.content').find('h2');
var h2ElemCount = h2Elements.length;
$(h2Elements).each(function(i) {
  $(this).prepend(h2ElemCount - i + '. ');
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script><divclass="content"><h1>Name of article</h1><h2>Subtitle</h2><p>.....</p><h2>Subtitle</h2><p>.....</p><h2>Subtitle</h2><p>.....</p><h2>Subtitle</h2><p>.....</p></div>

Solution 3:

Try This:

var h2Length = $("h2").length;
$("h2").each(function(i,obj) { 
  $(obj).html(h2Length +". "+$(obj).html());
  h2Length--; 
});

Post a Comment for "Jquery Automatic Heading Numbering"