Rashmi Kumari
Rashmi Kumari

Reputation: 530

How to get child element value separated by comma in jQuery

I have a list:

<ul class='class-name'>
  <li><p>value1</p></li>
  <li></li>
  <li><p>value2</p></li>
  <li><p>value3</p></li>
</ul>

I want to get value1,value2,value3. I'm using:

$('ul.class-name > li > p').text();

But I'm getting value1value2value3.

Can anyone tell me how to get a comma separated value?

Upvotes: 9

Views: 3366

Answers (1)

alex
alex

Reputation: 490489

You could try this...

$('ul.class-name > li > p')
    .map(function() { return $(this).text(); }).get().join();

jsFiddle.

This gets all the p elements, iterates over them replacing their references with their text, then gets a real array from the jQuery object, and joins them with join() (the , is the default separator).

Upvotes: 15

Related Questions