blam4nz
blam4nz

Reputation: 21

Numeration in jQuery

I wanna achieve numeration in jQuery. My current code works fine, but works for each div(.menu-item), I need separately.

My current code:

$('.menu-item h3').each(function (i) {

    ++i;

    $(this).find('span').text(i + '.');

});

Current effect:

.menu-item
    1.
    2.
    3.

menu-item#2
    4.
    5.
    6.

Need:

.menu-item
    1.
    2.
    3.

menu-item#2
    1.
    2.
    3.

HTML Code:

<div class="menu-item">
 <table>
  <tr>
   <td>
    <h3><span></span> Title</h3>
   </td> 
  </tr>
 </table>
</div>

Upvotes: 1

Views: 78

Answers (3)

Spencer Wieczorek
Spencer Wieczorek

Reputation: 21575

You will want to go to each menu-item, then go though each h3 in that. This way the i in the .each() function is reset for each menu-item you have:

$('.menu-item').each(function () {
    $(this).find("h3").each(function(i) {
        $(this).find('span').text(++i + '.');
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="menu-item">
    <h3>
        <span></span>
    </h3>
    <h3>
        <span></span>
    </h3>
    <h3>
        <span></span>
    </h3>    
</div>

<div class="menu-item">
    <h3>
        <span></span>
    </h3>
    <h3>
        <span></span>
    </h3>
    <h3>
        <span></span>
    </h3>    
</div>

Upvotes: 0

j08691
j08691

Reputation: 207923

You can use jQuery's .index() function to do this as by default .index() looks only at sibling elements:

$('.menu-item h3').each(function () {
    $(this).find('span').text($(this).index()+1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="menu-item">
     <h3>
        <span></span>
    </h3>

     <h3>
        <span></span>
    </h3>

     <h3>
        <span></span>
    </h3> 
</div>
<div class="menu-item">
     <h3>
        <span></span>
    </h3>

     <h3>
        <span></span>
    </h3>

     <h3>
        <span></span>
    </h3> 
</div>

After seeing your HTML, you can use $('.menu-item tr') instead of $('.menu-item h3').

Upvotes: 2

tompave
tompave

Reputation: 12427

You should "scope" i inside each .menu-item.

Try with:

$('.menu-item').each(function(index, $item){
    $item.find('h3').each(function(index, $h3) {
        $h3.find('span').text(++i + '.');
    });
});

Upvotes: 0

Related Questions