Locating child of a nearby ancestor with jQuery

Posted on

Problem

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>
<div class="one mobile-one columns">
  <span class="postfix">
    <a href="#" id="startdatecalicon" class="dpicon"><i class="foundicon-calendar infoicon"></i></a>
  </span>
</div>

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

$(".dpicon").click(function(){
  $(this).parent().parent().prev().children(".dpicker").focus();
});

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?

Solution

I would make the link between the 2 implicit.

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

Then the code is

$(".dpicon").click(function(){
  $( 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

$(".dpicon").click(function(){
  $( this.getAttribute( "data-dpicker" ) ).focus()
}

Leave a Reply

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