Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get parent id by onclick on a child in js? [duplicate]

Tags:

javascript

    <div id="rnd()"><button onclick="checkId()">Click</button></div>

I have a DIV when I make by DOM in JS and has a random ID, his child this button.

I need at the click of a button I can know what the ID of the parent (DIV).

like image 599
akosem Avatar asked Feb 13 '17 21:02

akosem


1 Answers

You need to update your function call to include this:

<div id="rnd()"><button onClick="checkId(this)">Click</button></div>

<script>
function checkId(elem)
{
    alert(elem.parentNode.id);
}
</script>

or add the event using javascript and give your button an id like this:

<div id="rnd()"><button id="myBtn">Click</button></div>
<script>
    document.getElementById("myBtn").onclick = function(e){
      alert(e.target.parentNode.id);
    }
</script>
like image 83
Neri Barakat Avatar answered Oct 19 '22 02:10

Neri Barakat