user3420034
user3420034

Reputation:

Get value of <span> based on other <span> class within div?

So I have the following HTML:

<div class="calculator-section">
    <p>
        <span class="x"></span>
        <span class="amount">30</span>
    </p>
    <p>
        <span class="y"></span>
    </p>
</div>

What I want to do is get the number inside the <span> with class 'amount' within each calculator-section based on the span with class 'x'. There can be multiple divs with the class 'calculator-section' and multiple <p> within those with varying spans.

Roughly what I want to do (I'm aware this won't work, it's just to show what I'm trying to do):

var amount = 0;

$('.calculator-section p').each(function(i, obj) {
    if($(this).$('span').className == "x") {
        //Set 'amount' variable to value within <span> with class 'amount' within the same <p>.
    }
});

Hopefully this example makes sense. Any ideas?

Upvotes: 0

Views: 849

Answers (2)

MH2K9
MH2K9

Reputation: 12039

Try this

var amount = 0;
$('.calculator-section p span').each(function(i, obj) {
    if($(this).attr('class') == "x") {
        amount = $(this).next('.amount').text();
        return false;
    }
});
alert(amount);

Upvotes: 0

David Thomas
David Thomas

Reputation: 253318

I'd suggest:

$('.calculator-section p .x').text(function () {
    return $(this).next('.amount');
});

References:

Upvotes: 1

Related Questions