HTML
<div class="topparent">
<div class="secondparent">
<div class="firstparent">
<a href="#" class="link" >Menu Link</a>
</div>
</div>
</div>
here I want to get <div class="secondparent"> by jQuery or JavaScript. My code would be on Anchor Tag and i want to get its second most parent element by Index number. Or is there any other way? I don't want get element by hard coded ID or CLASS.
You can use parents() and eq()
parents() you can get all ancestorseq() will help to select by indexCODE:
var p1=$('a.link').parents().eq(0);
var p2=$('a.link').parents().eq(1);
var p3=$('a.link').parents().eq(2);
console.log(p1.attr('class'),p2.attr('class'),p3.attr('class'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="topparent">
<div class="secondparent">
<div class="firstparent">
<a href="#" class="link" >Menu Link</a>
</div>
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With