Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery get all data attributes from a list

I have a long dynamically generated list each with the same class identifier and a data attribute similar to the code below:

<ul>
    <li class="list" data-id="123">One</li>
    <li class="list" data-id="124">Two</li>
    <li class="list" data-id="125">Three</li>
    <li class="list" data-id="126">Four</li>
    .....etc
</ul>

what I am trying to achieve is to get all the data-id values and format them in as follows:

123|124|125|126....etc

this would be then passed to a page via ajax and the id's checked for existence in a database.

var delimited_data="";
$('.list').each(function(){
    delimited_data+=$(this).data('id')+"|";
});
console.log(delimited_data);

The reason I am asking this question is that I am working on a live system that automatically deploys items in the list columns to different users after 10 mins. I just need to be sure that the code is going the right way :)

I also need to check that is there are no .list classes on the page (ie - no way to do the query) whether delimited_data will be totally empty which I am pretty sure it would be.

Is there a better way than using .each() in this case as I find it can be rather slow baring in mind that the above function will be run every 30 seconds.

like image 474
14 revs, 11 users 47% Avatar asked Sep 06 '25 13:09

14 revs, 11 users 47%


1 Answers

You can use .map to return an array:

var dataList = $(".list").map(function() {
    return $(this).data("id");
}).get();

console.log(dataList.join("|"));

Demo: http://jsfiddle.net/RPpXu/

like image 81
tymeJV Avatar answered Sep 08 '25 12:09

tymeJV