Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get child element value separated by comma in jQuery

Tags:

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?

like image 681
Rashmi Kumari Avatar asked Nov 16 '12 04:11

Rashmi Kumari


People also ask

How to find children of selected element in jQuery?

children() is an inbuilt method in jQuery which is used to find all the children element related to that selected element. This children() method in jQuery traverse down to a single level of the selected element and return all elements. Syntax: $(selector).children() Here selector is the selected element whose children are going to be found.

How to count the number of children of a jQuery element?

For instance, you can use jQuery n th child selectors which can count children from the last to first, select jQuery first child, or do other tasks that depend on sibling relations. jQuery .children () method traverses downwards a single level of the DOM tree and looks for descendants of specified elements.

What is the children () method in jQuery?

Last Updated : 13 Feb, 2019 children () is an inbuilt method in jQuery which is used to find all the children element related to that selected element. This children () method in jQuery traverse down to a single level of the selected element and return all elements.

How do I use jQuery children() when traversing downwards?

When traversing downwards, jQuery .children () returns all direct children and traverse one level down the DOM tree. Here is a code example to illustrate how this method is used: The method returns the direct children of the element you select, and uses syntax like this:


1 Answers

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).

like image 82
alex Avatar answered Oct 11 '22 16:10

alex