Count back

Asked

Viewed 102 times

1

Good morning gentlemen,

I need to count elements of a li and add these values dynamically by counting the previous li elements:

 <div class="conteudo">
            <ul>
                <li><i class="indice">1 - </i>Conteudo 1</li>
                <li><i class="indice">2 - </i>Conteudo 2</li>
                <li><i class="indice">3 - </i>Conteudo 3</li>
                <li><i class="indice">4 - </i>Conteudo 4</li>
                <li><i class="indice">5 - </i>Conteudo 5</li>
                <li><i class="indice">6 - </i>Conteudo 6</li>
            </ul>
        </div>
The idea is that the 'i' elements of the class ="Indice" receive each its index dynamically. Since I’m new to jquery I’m having trouble performing this function, would anyone have an idea of how I can solve this? I hug you all!

  • uses each and addClass() http://api.jquery.com/each/ http://api.jquery.com/addClass/

  • Good day periotto, does each count the right elements? if yes, my doubt is how I would make him count only the previous elements and pass this value to the . Indice! Hug!

1 answer

3


$(function(){


  $('#add').click(function(){
      var count = $("ul").children().length;
      $('ul').append('<li><i class="indice" rel="'+(count+1)+'" >'+(count+1)+' - </i>Conteudo '+(count+1)+'</li>');
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="conteudo">
  <ul>
    <li><i class="indice" rel="1" >1 - </i>Conteudo 1</li>
    <li><i class="indice" rel="2" >2 - </i>Conteudo 2</li>
    <li><i class="indice" rel="3" >3 - </i>Conteudo 3</li>
    <li><i class="indice" rel="4" >4 - </i>Conteudo 4</li>
    <li><i class="indice" rel="5" >5 - </i>Conteudo 5</li>
    <li><i class="indice" rel="6" >6 - </i>Conteudo 6</li>
  </ul>
  
  <button id="add">Adicionar</button>
</div>

  • 1

    That’s exactly what it was, Jefferson! Hug!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.