<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).
<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).
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>
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.
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");