0

I have these 3 divs

Is there a way to get the id parent when you click on that child of child, and if yes, how?

function getParentId(el) {
  //get the id "parent"
}
<div id="parent">
  <div class="child">
    <div class="child-of-child" onClick="getParentId(this)">
      <!-- some code here -->
    </div>
  </div>
</div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
emma
  • 761
  • 5
  • 20

2 Answers2

2

You can use Node.parentNode:

function getParentId(el){
   var p = el.parentNode.parentNode;
   console.log(p.id);
} 
<div id="parent">
    <div class="child">
        <div class="child-of-child" onClick="getParentId(this)">
        <!-- some code here -->
        Click
        </div>
    </div>
</div>
Mamun
  • 66,969
  • 9
  • 47
  • 59
1

You can use el.parentElement inside the click function:

function getParentId(el){
   var id = el.parentElement.parentElement.id;
   console.log(id);
}
<div id="parent">
    <div class="child">
        <div class="child-of-child" onClick="getParentId(this)">
        click
        </div>
    </div>
</div>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62