brad_k
brad_k

Reputation: 23

jQuery return text from span tags based on label tags

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

Answers (3)

Matyas
Matyas

Reputation: 13702

You should do:

var $yourspan = $('label:contains(Claim.Claimant)').parent().find('span')

Basically it

  • finds a label containing a specific text
  • finds its parent
  • in this parent element searches for a span

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

user1094553
user1094553

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

Rory McCrossan
Rory McCrossan

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.

Example fiddle

Upvotes: 2

Related Questions