简体   繁体   中英

Javascript get id of parent div

I have the following structure:

<div id="accord1_1" class="panel-collapse collapse">
 <div class="panel-body">
   <div id="Dashboard">
    <div id="DashboardFlow">
     <div class="dashboard-caps">
      <div class="dashboard-info">
          <a class="save" onclick="return saveChanges();" href="#">Save</a>

When clicking on Save button i would like to get the parent div that is like accord%_1 . I'll explain myself better:

I have like 30 structures like the one i've shown created. All of them are exactly the same except from the id="accordX_1" key which is id="accord1_1" in the first collapsable panel, id="accord2_1" in the second and so on.

What i need to do is get that id's value.

How can this be done?

Regards,

Use closest and the startsWith selector

$('.save').click(function(){
 var targetId = $(this).closest('div[id^=accord]')[0].id;
}); 

This will find the first matching parent element in the list of parent elements for the element with class=save, access the matched native element with [0], and the native .id property.

Just find the closest div on clicking save

$("a.save").click(function(){

    var curr = $(this).closest("div.panel-collapse[id^=accord]") // Is the div you want;
    var id = curr.attr("id");

});

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