Tom
Tom

Reputation: 11

Return the text of each span using JQuery

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

Upvotes: 1

Views: 2606

Answers (3)

user213154
user213154

Reputation:

or

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

a bit boring but easy to understand.

Upvotes: 0

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827396

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

Upvotes: 7

Rich
Rich

Reputation: 3123

$("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()]); }, [])

Upvotes: 1

Related Questions