How do I select the child of the third previous DOM element?
I have it:
<div ><a href='#' id='my_target'>Link</a></div>
<div></div>
<div><div></div></div>
<div><div id='my_div'></div></div>
How can I choose #my_target
when the event is fired from my_div
?
I've tried things like prev().prev().prev().children()
but I can't get it to work and I want something more efficient.
source to share
Alternatively, you can also use relative paths: HTML:
<div><a href='#' id='my_target'>Link</a></div>
<div></div>
<div><div></div></div>
<div><div id='my_div'></div></div>
JS:
$(document).ready(function() {
console.log($("#my_div").parent().parent().children(':first'));
});
JSFiddle: http://jsfiddle.net/5Bf6g/
source to share
I did it like this:
var md = $("#my_div");
var anchor = $(md.parent().prevAll().last().find("a"));
console.log(anchor);
JSFiddle: http://jsfiddle.net/t9HZz/
prevAll()
grabs all parent siblings, and then we take the last one from last()
, because it adds siblings in reverse order, then we can just find the link from there.
Although in your example the link has an id, so you can just do $("#my_target")
in this particular example.
source to share