Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a comma-separated list of IDs in JavaScript?

So I have a <ul> that contains <li> elements, and I'd like to grab the IDs of these out and pass them on in a querystring to another page.

Like so:

<ul id="myList">
   <li id="first">First</li>
   <li id="second">Second</li>
   <li id="third">Third</li>
</ul>

into

first,second,third

Is there a neat way to do this? I've jQuery, so my brute-force probably-not-very-good-approach is to iterate using each() and build it that way. A bit scruffy, I think.

like image 869
Jeremy McGee Avatar asked Dec 27 '22 09:12

Jeremy McGee


1 Answers

A short and neat way using .map:

var ids = $("#myList li").map(function() {
    return this.id;
}).get().join(",");
like image 171
karim79 Avatar answered Mar 24 '23 12:03

karim79