If we have nested divs one inside another and we want to get id of parent div for this we use parents().
suppose following div structure
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | <div class="level1" id="level1_123"> <div class="level2" id="level2_324"> <div class="level3" id="level3_567"> <div class="level4" id="level4_985"> <input type="submit" value="Get Parent Id" id="submit"> </div> </div> </div> </div> |
1 2 3 4 5 6 7 | $(document).ready(function () { $(document).on('click', '#submit', function (event) { event.preventDefault(); var parentId = $(this).parents(".level1").attr("id"); alert(parentId); }); }); |
as above we have seen how to get id for top parent and similar we can get id or class value for any level of parent.
for getting class value we can use following which will give second level divs class based on its id value.
1 2 | var parentClass = $(this).parents(" #level2_324").attr("class");="" <="" pre=""><strong>Output</strong> <iframe width="100%" height="300" src="http://jsfiddle.net/ebhor/k8ykzLx2/embedded/result,js,html" allowfullscreen="allowfullscreen" frameborder="0"></iframe> |