user2810762 user2810762 - 1 month ago 4
Javascript Question

jQuery count each item and number them 02, 03, 04 except first item text should be "Up Next"

I am not great with jQuery, so far this is what i got from checking through stackoverflow and other resources:

var counter = 1;
$('.next-page .nav-item').each(function () {

if ($(this, ':gt(0)')) {
$(this).find('.view-title').html('Up Next');
} else {
$(this).find('.view-title').html('0' + counter);
}
counter++;

});


Basically the output should end up like this in the html:

<div class="nav-item">
<span class="view-title">Up Next</span>
<span>Kits</span>
</div>

<div class="nav-item">
<span class="view-title">02</span>
<span>GUI</span>
</div>

<div class="nav-item">
<span class="view-title">03</span>
<span>UI</span>
</div>

<div class="nav-item">
<span class="view-title">04</span>
<span>Other</span>
</div>

Answer

Try like

$('.next-page .nav-item').each(function (i , val) {
    $(this).find('.view-title').html(!i ? 'Up Next' : '0' + (i+1));
});
Comments