Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript How to get “data-” values under ul tag into a comma separated list?

  • This topic is empty.
Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
    Posts
  • #44236
    West415
    Participant

    Hi,

    Any help here definitely appreciated

    I have this HTML structure and I’m using jQuery 1.9.x and want to basically iterate through a series of `

  • ` tags and grab the value of a the HTML 5 data attribute (data-customerid) and build a comma delimited list of all the values. I can’t figure out how to format my message on here, but basically i have a UL with a named “id” and a series of li tags underneath with a href tags underneath each li. The href tags have a data attribute called “data-customerid”.

    • Row 1
    • Row 2
    • Row 3

    I should end up with a string like this in a variable `833,836,839`.

    How can I do this?

    Thanks…

#132392
Merri
Participant

One solution, there may be more elegant ways to do this:

var out = [];

$(‘#myList a’).each(function(){
out.push( $(this).attr(‘data-customerid’) );
});

var commas = out.join(‘,’);

.

#132424
SgtLegend
Member

Using the `attr` method in jQuery for `data-` attributes is technically correct but its recommended you use the `data` method which is designed for HTML5 data attributes, see the below example:

out.push($(this).data(‘customerid’));

#132472
West415
Participant

Thanks for the replies. I’m going to try the above out and I will post back my results. With jQuery it always seems like there is more than 1 way to do something.

#132660
West415
Participant

This worked… thanks.

Viewing 5 posts - 1 through 5 (of 5 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.