# Locating child of a nearby ancestor with jQuery

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?

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()
}

• +1 I definitely think the link between the two controls needs to be made explicit although I was thinking about using a data attribute - I like the inventive use of the href (but at the same time, I can't help thinking it's abusing it). :)
– RobH
Mar 19 '13 at 20:42
• Both good ideas thanks. I was trying for something that didn't require the existing inputs and links to have anything 'custom' about them (as the will be built dynamically by php) but using the ID like that will be fine! I think I'll use data-picker instead of href. Thanks! Mar 19 '13 at 22:30