Get date attribute of last element from a list

0

Good morning, I am putting together a system that when I click a button I add a <li> to the last row record, however every <li> has numeric data-id for differentiation, that is, I would need to know the last data-id to be able to add +1 by clicking the button.

I tried as a code below but it did not work, it just takes the first data-id (I need the latter) and does not add + 1 on the second click,

$("#botaoexemplo").on("click", function() {
    var contagem = $('.dd-item').attr('data-id');
    contagem++;
    $("#dd-list-geral").append('<li class="dd-item" data-id="'+contagem+'"><div class="dd-handle"> Item 100 </div></li>');
    console.log(valor, dado);
});
    
asked by anonymous 10.04.2018 / 14:06

3 answers

3

You can use last to get the last item from an array of elements in your selector:

var ultimoId = $('.dd-item:last').data('id');

Reference: link

    
10.04.2018 / 14:13
2

Use the function .last()

$("#botaoexemplo").on("click", function() {
    var contagem = $('.dd-item').last().attr('data-id');
    contagem++;
    $("#dd-list-geral").append('<li class="dd-item" data-id="'+contagem+'"><div class="dd-handle"> Item 100 </div></li>');
    console.log(valor, dado);
}); 
    
10.04.2018 / 14:17
1

To get the last element you can use the :last

For example, to get the last row of a table:

$('table tr:last')

Note that your append already inserts in the last position, then :last after append will be the line just included.

    
10.04.2018 / 14:14