Locating child of a nearby ancestor with jQuery

Posted on


I have the following markup, and I’m wondering how best to locate the nearest previous dpicker input element and give it focus with jQuery when a.dpicon is clicked.

<div class="eight mobile-two columns">
  <input autocomplete="off" class="dpicker" type="text" name="mdpdate" id="mdpdate">
<div class="one mobile-one columns">
  <span class="postfix">
    <a href="#" id="startdatecalicon" class="dpicon"><i class="foundicon-calendar infoicon"></i></a>

I’ve used this, and it works, but it seems pretty cumbersome:


Also, there will be times that the ‘dpicon’ element will be before the input in markup, not after it. Is there a way to catch both instances?


I would make the link between the 2 implicit.

<a href="#mdpdate" id="startdatecalicon" class="dpicon">

Then the code is

  $( this.href ).focus()

It is a creative (ab)use of href, but it still follows the spirit in my mind.

If you have the luxury of going HTML5, you can go with a data attribute.

<a href="#" id="startdatecalicon" class="dpicon" data-dpicker="#mdpdate">

Then the code is

  $( this.getAttribute( "data-dpicker" ) ).focus()

Leave a Reply

Your email address will not be published. Required fields are marked *