开发者

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

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

var tag_text_arr=开发者_JAVA百科$("#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...


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/


Use the jQuery map method to return an array of the text you want, then use join to concatenate them.

var x = $.map($("span"), function(item) {
    return $(item).text();
}).join("|");

alert(x);

jsFiddle here: http://jsfiddle.net/Ewdge/


var spanValues = [];
var tag_text_arr=$("#div_id span").each(function(){
    spanValues.push($(this).text());
});
var pipedSpanValues = spanValues.join("|");


var arr = $("span").get().map(el => el.textContent);

console.log(arr)
<span>Lorem</span>
<span>ipsum</span>
<span>dolor</span>
<span>sit amet</span>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


You've already got most of it done. You can

A. Append $(this).text()'s output to an array and .join() the array with a pipe, or
B. Concatenate $(this).text()'s output + a pipe symbol to a string and then remove the final pipe after the loop.


You were almost there...

var span_text = "";
$("#div_id span").each(function() {
    span_text += $(this).text() + "|";
});
var span_text.substring(0, span_text.length - 1); // remove the trailing | character.


Something like this should do the trick:

var result = $('#div_id').find('span').map( function(i,e){
  return $(e).text();
})
.get()      // Stop here for an array
.join('|'); // or here for a string


final val;

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

alert(val.substring(0,val.length-1));

this should do

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜