1

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

<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>

So, question is how to give number for each H2 tag (subtitle) automatically by jQuery in descending order?

<h1>Name of article</h1>
<h2>15.Subtitle</h2>
<p>.....</p>
<h2>14.Subtitle</h2>
<p>.....</p>
<h2>13.Subtitle</h2>
<p>.....</p>
<h2>12.Subtitle</h2>
<p>.....</p>

I know how to do it via CSS counters, but articles can contain different numbers of subtitles. I've checked similar Automatic Numbering of Headings H1-H6 using jQuery topic, but it is not i want exactly.

Community
  • 1
  • 1
Berber
  • 23
  • 7

3 Answers3

1

You can numerate backwards by using the each function.

allItems = $("h2").length;
$("h2").each(function (index){
  $(this).prepend(allItems - index + ". ");
});
<script src="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>
Neil
  • 14,063
  • 3
  • 30
  • 51
0

Try This:

var h2Length = $("h2").length;
$("h2").each(function(i,obj) { 
  $(obj).html(h2Length +". "+$(obj).html());
  h2Length--; 
});
Tanmay
  • 1,123
  • 1
  • 10
  • 20
0

This should help

var h2Elements = $('.content').find('h2');
var h2ElemCount = h2Elements.length;
$(h2Elements).each(function(i) {
  $(this).prepend(h2ElemCount - i + '. ');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="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>
Web pundit
  • 398
  • 3
  • 10
  • Thank you! It is exactly what I wanted. I've just put article tag instead of .content class. – Berber Apr 12 '17 at 16:46
  • One more question: How can I add some CSS class to stylize? I tried to use .addClass('.h2style'); but it doesn't work. – Berber Apr 12 '17 at 18:08
  • no need to put '.' (period) inside addClass, you can just do .addClass('h2style') – Web pundit Apr 13 '17 at 16:17
  • Maybe, can you help with another problem? http://stackoverflow.com/questions/43397234/h2-heading-numbering-doesnt-work-correctly-with-paginated-posts – Berber Apr 13 '17 at 18:53