Tsuna
Tsuna

Reputation: 2198

Couldn't find my span tag using jquery

I thought using closest goes up the DOM and find goes down the DOM isn't it?

I am trying to find a span element when an input has focusout. I am able to get the value of the input when focusout properly but couldn't find the span.

in my html I have something like this

              <div class="form-group">
                  <label for="card-holder-name">Card Holder Name: <span>eafsdafasdf</span></label>
                  <input type="text" class="form-control card-holder-name" id="card-holder-name">
              </div>

in jquery

$(".card-holder-name").on('focusout', function(){
var inputValue = $(this).val();
console.log($(this).closest('label').find('span').text();

});

I tried using console.log($(this).closest('label').text()); to just find the label but no luck.

What am I doing wrong here?

Thanks in advance

Upvotes: 0

Views: 98

Answers (2)

j08691
j08691

Reputation: 207861

.closest() does go up the DOM but you're trying to use it against a sibling.

Use .prev() in this case:

$(this).prev('label').find('span').text()

jsFiddle example

Upvotes: 4

willwolfram18
willwolfram18

Reputation: 1887

You're correct, $.closest() traverses up the DOM and $.find() traverses down. The issue you're having, however, is that label[for='card-holder-name'] is a sibling to input.card-holder-name.

For the specific HTML you're using, you could either go with $(this).prev("label") or $(this).parent().find("label").

Upvotes: 1

Related Questions