Reputation: 23
I have the following HTML rendered on my page:
<div class='panel'>
<div>
<div class='section'>
<ul class='properties'>
<li>
<label>Claim.Claimant</label>
<span class="value">Smith, John</span>
</li>
<li>
<label>Claim.LossDate</label>
<span class="value">04/22/2014</span>
</li>
<li>
<label>Claim.LossDescription</label>
<span class="value">I was injured.</span>
</li>
</ul>
</div>
</div>
</div>
I am trying to retrieve the text that is populated in the span tag using jQuery.
I've tried with zero success:
alert($("<label>Claim.Claimant</label>").find("span.value"));
Any ideas on what I'm doing wrong?
Upvotes: 2
Views: 2203
Reputation: 13702
You should do:
var $yourspan = $('label:contains(Claim.Claimant)').parent().find('span')
Basically it
See the live demo
Check out the documentation for contains
Edit:
According to this jsperf test Rory's answer is indeed more performant.
Upvotes: 5
Reputation: 796
You can get the text value of a span tag using .text()
This will get the text from all the span tags with class "value":
$("span.value").text()
If you want a specific span tag either assign unique IDs to each of them, or refer to them with an index:
$($("span.value")[0]).text()
Upvotes: 0
Reputation: 337627
First of all, your syntax for the selector is incorrect. You want to follow basic CSS rules, not encoded HTML in the selector. Then you can use filter()
to find an element by it's text. Try this:
var valueText = $('label').filter(function() {
return $(this).text() == 'Claim.Claimant';
}).next('span.value').text();
alert(valueText); // = 'Smith, John'
Note that filter()
is a lot faster than the :contains
selector.
Upvotes: 2