Pick last element attribute date from a list

Asked

Viewed 411 times

0

Good morning guys, I’m riding a sisteminha that by clicking a button I add a <li> in the last record of the line, but each <li> has a data-id numerical for differentiation, i.e., I would need to know which last data-id to add + 1 when clicking the button.

I tried as code below, but it didn’t work, it just picks up the first data-id (i need the last) and does not add + 1 in the second click, only in the first.

$("#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);
});

3 answers

3


You can use last to take the last item of an array of elements from its selector:

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

Reference: https://api.jquery.com/last/

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);
}); 

1

To catch the last element you can use the selector :last

For example, to take the last line of a table:

$('table tr:last')

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

Browser other questions tagged

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