Tsuna Tsuna - 2 months ago 6
CSS Question

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

Answer

.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

Comments