最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Return the text of each span using JQuery - Stack Overflow

programmeradmin0浏览0评论

Im able to get the list of all spans having the attribute dir='somevalue', with the following jquery statement

$("span[dir='somevalue']")

I want the text of each span i.e. for example, <span dir='somevalue'> text </span>, i need the value 'text', and i want this for every span returned by the previous statement. Any way to do this using Jquery ?

Thank You

Im able to get the list of all spans having the attribute dir='somevalue', with the following jquery statement

$("span[dir='somevalue']")

I want the text of each span i.e. for example, <span dir='somevalue'> text </span>, i need the value 'text', and i want this for every span returned by the previous statement. Any way to do this using Jquery ?

Thank You

Share Improve this question asked Dec 20, 2009 at 17:26 TomTom 111 silver badge2 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

I think is a good case to use Traversing/map:

var values = $("span[dir='somevalue']").map(function(){
  return $(this).text();
}).get();

The values variable is now an Array that contains on each array element the inner text of each span matched by your selector.

If you want to concatenate all the values in a string, you can use Array.prototype.join:

var allValues = values.join(" "); // using a space as separator between values
$("span[dir='somevalue']").text()

will give you the concatenation of all the text. If you want an array and are using Javascript 1.8 you can use

$("span[dir='somevalue']")
    .get()
        .reduce(function (a,b) { return a.concat([$(b).text()]); }, [])

or

var values = [];
$("span[dir='somevalue']").each(function(){
    values.push($this.text());
});

a bit boring but easy to understand.

发布评论

评论列表(0)

  1. 暂无评论