简体   繁体   中英

Get parent div id by clicking on a child element

What I'm looking to do is remove the parenting div by ID after the button is clicked, to avoid closing all divs with the same class. In my actual code, the user is able to append multiple divs to the screen on button click, and each is assigned it's own ID. Each has a boostrap button up top that should close the parent div only instead of having to create 12 separate functions (the limit of div placement for the user).

HTML

<div class='some classes' id='box1'>
<span class='btn btn-primary'>Close this div</span>
</div>
<div class='some classes' id='box2'>
<span class='btn btn-primary'>Close this div</span>
</div>

CSS

#box {
  width:200px;
  height:200px;
  background:black;
}

JS

$(document).ready(function(){
  $('.btn').on('click',function(){
    var getParentID = $('.btn').parent().attr('id');
    $(getParentID).remove();
});
});

This is essentially all I was working with to try to get it to function. Any help is much appreciated!

Use $(this) instead of $('.btn') since you want to target the specific element

var getParentID = $(this).parent().attr('id'); Once the id is available use jquery id selector to target the element

 $(document).ready(function() { $('.btn').on('click', function() { var getParentID = $(this).parent().attr('id'); $("#" + getParentID).remove(); }); }); 
 #box { width: 200px; height: 200px; background: black; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class='some classes' id='box1'> <span class='btn btn-primary'>Close this div</span> </div> <div class='some classes' id='box2'> <span class='btn btn-primary'>Close this div</span> </div> 

Note: The answer is specific to your question.Alternatively the parent div can be removed even without getting it's id

What you want to do is to skip the jQuery and do it in pure javascript.

var parent = child.parentElement;
parent.parentElement.removeChild(parent);

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