Reputation: 4633
I made a div, in a div, in a div and I am trying to access the attribute food
of the extern div through the most intern div. How can I do that?
I commented in the code, I'm trying to alert 'banana'.
//alert($('.animals').attr('food')); //alerts banana
//alert($('.mammals').parent().attr('food')); //alerts banana
//alert($('.monkeys').parent().parent().attr('food')); //doesn't alert banana
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="animals" food="banana">
<div class="mammals">
<div class="monkeys">
</div>
</div>
</div>
Upvotes: 1
Views: 441
Reputation: 579
You can use closet() or parentsUntil(). With parentsUntil, you can even select multiple parents
alert($('.monkeys').parentsUntil(".animals").attr("food"))
Upvotes: 1
Reputation: 16068
You can use parents for multiple levels:
$('.monkeys').parents('.animals').attr('food')
Upvotes: 3
Reputation: 62488
You can use closest()
to get to specific parent element of a child element
:
alert($('.mammals').closest(".animals").attr('food'));
alert($('.monkeys').closest(".animals").attr('food')
See closest() in Jquery DOCS here
Upvotes: 4
Reputation: 104775
Use closest
alert($('.monkeys').closest(".animals").attr("food"))
Upvotes: 2