Search code examples
jqueryautomationhtml-headingcss-counter

jQuery automatic heading numbering


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.


Solution

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