Jeremy McGee
Jeremy McGee

Reputation: 25210

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.

Upvotes: 4

Views: 4523

Answers (1)

karim79
karim79

Reputation: 342715

A short and neat way using .map:

var ids = $("#myList li").map(function() {
    return this.id;
}).get().join(",");

Upvotes: 10

Related Questions