adit
adit

Reputation: 33654

finding the closest element with a particular id

I have the following html:

 <div class="col-xs-12 col-sm-7 col-md-8 form-group">
    <input id="contact-info" class="form-control input-lg" name="contactInfo" placeholder="LINE ID" type="text" required autofocus />
 </div>
 <div class="col-xs-12 col-sm-5 col-md-4 form-group">
    <select class="form-control contact-type input-lg" name="contactType">
 <div>

Given an contact-type, how do I find the closest contact-info to that contact-type?

I tried doing the following but it failed:

$('.contact-type').closest('#contact-info')

Any idea what's wrong?

Upvotes: 0

Views: 4088

Answers (1)

Felix
Felix

Reputation: 38102

Based on your HTML markup, you can do:

$('.contact-type').closest('div').prev().find('#contact-info')

closest()

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

so closest() is not applicable in your case to get #contact-info because #contact-info is the child of a div which is the previous sibling of the parent div of your .contact-type

But since id is unique, you can just use:

$('#contact-info')

Upvotes: 2

Related Questions