Ronnie Overby
Ronnie Overby

Reputation: 46470

jQuery closest() not working for me (or i'm not working for it)

Given this jQuery:

$('div.MvcFieldWrapper :input').focus(function() {
      $(this).closest('label.MvcDynamicFieldError').fadeOut();
});

And given this HTML:

<div class="MvcFieldWrapper">
    <label class="MvcDynamicFieldPrompt">Enter your email address:</label>
    <label class="MvcDynamicFieldError">Required</label>
    <input type="text" value="" />
</div>

Why is the label not fading out when I focus on the input? I know for sure that the focus event is happening.

Thanks

Upvotes: 3

Views: 3822

Answers (1)

Doug Neiner
Doug Neiner

Reputation: 66191

Closest looks through the "parents" not siblings. What you want is prevAll:

$('div.MvcFieldWrapper :input').focus(function() {
      $(this).prevAll('label.MvcDynamicFieldError').fadeOut();
});

closest actually means "find the closest ancestor that matches the selector, including the already selected element if it meets the requirements."

Upvotes: 13

Related Questions