JQuery get all data attributes from a list

Issue

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.

Solution

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/

Answered By – tymeJV

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published