How to get the value of a child 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 use:

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

But I get value1value2value3 .

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

+7
source share
1 answer

You can try this ...

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

jsFiddle .

This gets all the elements of p , iterating over them, replacing their references with their text, and then gets the real array from the jQuery object and connects them to join() ( , is the default delimiter).

+13
source

All Articles