13
    <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).

peterh
  • 11,875
  • 18
  • 85
  • 108
akosem
  • 147
  • 1
  • 1
  • 3

3 Answers3

25

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>
Neri Barakat
  • 1,555
  • 20
  • 25
3

One way would be to assign it a class and then just use jQuery to get the id such as this:

$('.check-id').on('click', function(){
    alert($(this).parent().attr('id'));
});

Your div would look like this:

<div id="rnd()"><button class="check-id">Click</button></div>

With the above approach you can have many buttons and divs and this would work. You just have to make sure to assign a check-id class to the button.

Bagzli
  • 6,254
  • 17
  • 80
  • 163
3

You should update the function to take in 'this' So like the following:

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

Then within the checkId function you should have the following:

var parentDiv = this.parentNode;
var id = parentDiv.getAttribute("id");
Liam's musings
  • 167
  • 4
  • 9