简体   繁体   中英

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?

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM