Mxaza
Mxaza

Reputation: 544

Reading a span tag's value using jQuery

I am trying to read the text value of a span tag that is inside a td tag in a table. I want to access only that span's value only but i fail, as each time the entire row's text is returned:

<table>
<tr>
<td> The cell i want <span style="color:#0000FF;"> I want this!! </span> </td>
<td>Not this</td>
</tr>
</table>

I tried using:

$("table tr span[style='color:#0000FF']:first");

Upvotes: 1

Views: 143

Answers (5)

Mxaza
Mxaza

Reputation: 544

Thank you all for you working and useful solutions. Upon implementing them my problem was solved but my mistake was not taking into consideration the entire page where this span is.

On its own this was easy(with your help of course!) but when it is part of a huge page that contains other controls it is difficult. So using the id attribute has made things simpler.

Upvotes: 0

Felix
Felix

Reputation: 38102

You can do:

$("table tr:first td:first span:first").text();

or simply:

$("table").find("span:first").text(); 

or

$("table span:first").text();

or

 $("table span:eq(0)").text();

Upvotes: 0

Raja Jaganathan
Raja Jaganathan

Reputation: 36117

You can simply use this to get the span text

$("table tr td:first span:first").text();

or

$("table tr td:eq(0) span:first").text();

LIVE DEMO

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074028

I tried using:

$("table tr span[style='color:#0000FF']:first");

That would actually work, if you made the selector exactly match the element (you're missing the ; after the color value — either remove it from the element's style attribute, or add it to the selector). (And if you use .text() to get the text of the span.) Live Example

But it's really fragile. If there's any other way you can identify that span, use the other way. For instance, it's the first span within the td, so:

var text = $("table tr span:first").text();

...would work, if you can rely on that.

Note that in both cases, you'll get the text from the first row that contains a matching span; subsequent rows will be ignored.

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82231

Use jquery text():

$('table tr td:first span').text()

Upvotes: 0

Related Questions