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
  • 155,085
  • 27
  • 166
  • 222
emma
  • 731
  • 5
  • 18

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
  • 62,450
  • 9
  • 45
  • 52
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
  • 29,658
  • 5
  • 35
  • 59