KubiRoazhon KubiRoazhon - 6 months ago 13
HTML Question

How to get a list of values with jquery each function

I'm trying to get data value from an

<li data-nid="1">
tag. The
<li>
list is generated from an
Ajax
query response.

$.each(data.notifications.detail,function(index, element){
$('#notifications_list').append('<li id="element" data-nid ='+element.id+'><a>'+element.texte+'</a></li>');
});


to recover value, I tried the following method :

var array = new Array();
$( "#element").each(function() {
var id = $( this ).data( "nid" );
array.push(id);
});


But i'm always getting just one element, and its always the first one. So maybe someone clarify me the situation.

Answer

Firstly you cannot have multiple elements with the same id, hence the point of using an each() on an id selector is completely redundant. You should change the id to a class.

To create the array of values from the appended elements you can simply use map(). Try this:

$.each(data.notifications.detail, function(index, element){
    $('#notifications_list').append('<li class="element" data-nid="' + element.id + '"><a>' + element.texte + '</a></li>');
});

var array = $(".element").map(function() {
    return $(this).data("nid");
}).get();

Also note that you could create the array of values in the same each() loop as you append the new li elements, like this:

var array = [];
$.each(data.notifications.detail, function(index, element){
    array.push(element.id);
    $('#notifications_list').append('<li class="element" data-nid="' + element.id + '"><a>' + element.texte + '</a></li>');
});