Brian Powell
Brian Powell

Reputation: 3411

accessing different elements of an HTML tag

I have a button:

<a href="#" id="form-submit" class="btn btn-primary btn-lg ladda-button" 
data-style="contract" data-size="l">
    <span class="ladda-label">TESTLABEL</span>
</a>

and I'm trying to access the text inside of it: TESTLABEL through an IF statement. I can change the text like this:

$('#form-submit').text('GO').button("refresh");

but this if/else statement runs the first set of code each time - never the else if part.

console.log($('#form-submit').text());

if ($('#form-submit').text('TESTLABEL')) {
    $('#form-submit').text('GO').button("refresh");
} 
else if ($('#form-submit').text('GO')) {
    //do other code...
}

When I click the button - the text is TESTLABEL, and that changes to GO once I click. When I click again, the console.log tells me that this button's text is GO, but the first if statement still runs as though its text were TESTLABEL. What am i doing wrong?

Upvotes: 1

Views: 32

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337713

Firstly the text is inside the span element within the #form-submit element, so you should use $('#form-submit span') or $('#form-submit .ladda-label') to select it.

Secondly, in your if statement you're using the setter version of the text() method. This will always equate to true as the method returns a jQuery object. Instead, use the getter. Try this:

var $button = $('#form-submit')
var $label = $button.find('span');
if ($label.text() == 'TESTLABEL') {
    $label.text('GO');
    $button.button("refresh");
} 
else if ($label.text() == 'GO') {
    //do other code...
}

Upvotes: 4

Related Questions