Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to fetch all span values in a div as an array or string?

Tags:

jquery

I need to fetch all span values in a div into array or string

var tag_text_arr=$("#div_id span").each(function(){
        return $(this).text();
    });

Actually i need to fetch all span values inside div and want to create a string like this

span1_val|span2_val|span3_val|span4_val

If this is possible explain me...

like image 923
Mohan Ram Avatar asked Dec 02 '10 16:12

Mohan Ram


1 Answers

This should output your required string:

var arr = [];
$("#div_id span").each(function(index, elem){
    arr.push("span" +index+ "_" + $(this).text());
});
return arr.join("|");

Working demo: http://jsfiddle.net/HmUUB/

This will start the numbering at span0, not span1. If you want it to start at span1, use +(index + 1)+ instead of +index+. (example)


If I read your question wrong (and you don't want spann_ prefixed to each element in the string, you can just use jQuery's $.map() function:
var tag_text_arr = $.map($("#div_id span"), function(elem, index){
    return $(elem).text();
}).join("|");

return tag_text_arr;

Working demo: http://jsfiddle.net/BQLj6/

like image 102
Andy E Avatar answered Sep 21 '22 15:09

Andy E