views:

150

answers:

3

Hello,

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

+1  A: 
$("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()]); }, [])
Rich
CMS's version is much nicer than mine!
Rich
+2  A: 

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
CMS
A: 

or

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

a bit boring but easy to understand.

fsb
Should be values.push($(this).text()); of course.
Rich