Jquery - an array of selected children, separated by commas [allowed]

I need to create such an array in jQuery:

one,two,three,four 


selecting text from several <span> children:

 <div id="GROUP"> <div><input value="somevalue"/><span>one</span></div> <div><input value="somevalue"/><span>two</span></div> <div><input value="somevalue"/><span>three</span></div> <div><input value="somevalue"/><span>four</span></div> </div> 


I tried with this:

 $('html').find('#GROUP span').text(); 

But it combines the entire text without spaces:

 onetwothreefour 


I need to separate the text with commas


Thanks so much for your generous help :)

Working demo

+7
jquery text
source share
2 answers

Try using .map() along with .get() to collect these values ​​in an array, after .join() this array with any character you want.

 var text = $('#GROUP span').map(function(){ return $(this).text(); }).get().join(); 

Demo

Side Note: By default, .join() to text using .join() Therefore, there is no need to indicate this in our case.

+7
source share

To get them in an array you can use:

 var spantexts= []; $("#GROUP span").each(function() { spantexts.push($(this).text()) }); 

Demo

To get them as a comma value:

Using join:

 console.log(spantexts.join(',')); 

or

 var spantexts= ""; $("#GROUP span").each(function() { if(spantexts!="") spantexts+=","; spantexts+=$(this).text(); }); 

Working demo

+1
source share

All Articles