How to find parent container of an element using jQuery

For finding the parent of an element, there are built-in functions in jQuery like .parent() or .parents() which return the immediate parent element or all the parents in the hierarchy respectively for an element.

This method would work in some cases but mostly you would like to find a particular parent of an element, not just the immediate one nor the list of all parents in the hierarchy.

The correct way of doing this is to compose you query using parent’s selector with child(known element)’s selector as a filter applied on it. For example you have HTML like this.

 <style type="text/css">
.divlevel1{border: 2px solid gray; background-color: aqua; width: 500px; height: 600px;}
.divlevel2{border: 2px solid gray; background-color: fuchsia; width: 400px; height: 300px;}
.divlevel3{border: 2px solid gray; background-color: teal; width: 200px; height: 100px;}
</style>
<script type="text/javascript">
$(document).ready(function () {
$("#myButton").click(function () {

});
});
</script>
<div class="divLevel1">
<div class="divLevel2">
<div class="divLevel3">
<input id="myButton" type="button" value="Change Color" />
</div>
</div>
<div class="divLevel2">
<div>
</div>
</div>
</div>

on the click of button i want to change css of the button’s parent which is two levels up in the hierarchy. one way of doing this is,

$(this).parent().parent().css("border", "3px solid red");

this method will be very unreliable as you go up in the hierarchy. it is not a good approach to add chains to .parent().parent() .

consider this code,

$("div.divLevel2:has(input[id=" + $(this).attr("id") + "])").css("border", "3px solid red");

here i have selected div with class divlevel2 but only the one which has the buttons being clicked in of its children. so instead of going from child to parent, we went from parent to child.

final code will look like this.

$(document).ready(function () {
$("#myButton").click(function () {
$("div.divLevel2:has(input[id=" + $(this).attr("id") + "])").css("border", "3px solid red");
});
});

No comments:

LinkWithin

Related Posts with Thumbnails