简体   繁体   中英

how to get the id of parent by clicking child in jquery

I want to get the id of parent div when clicking child but can't find any logic to do that. Let take the following example:-

<div class="something" id="mainParentDiv">
    <div class = "childClass" id = "parent1">
       <div id = "child1" class = "smallestChild">
       </div>
    </div>
</div>

How can I get the id "parent1" by clicking "smallestChild"? I'm new in JQuery so sorry if this question is so naïve or basic. I am really unable to find solution for this. There are other questions but they are asking for getting child's id by clicking parent. Thanks in advance. Any help would be appreciated.

Try this way

 $('.smallestChild').click(function(){ $(this).parent().attr('id'); console.log($(this).parent().attr('id')); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="something" id="mainParentDiv"> <div class = "childClass" id = "parent1"> <div id = "child1" class = "smallestChild">Button </div> </div> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM