GoMega54 GoMega54 - 2 months ago 7
HTML Question

Target parent element within a child element's onclick event hander

Is it possible to target the ID of a parent div with an event handler in javascript?

Given the following code, when you click the image an alert fires containing the ID of the image "two". Is it possible to return "one", which is the ID of the parent div, appear in this box instead?



<div id="one">
<p>Some Text</p>
<img src="http://placehold.it/48x48" alt="" id="two" onclick="random(id)" />
</div>

<script>
function random(id) {
alert("working" + " " + id);
}
</script>




Answer

You can do this.parentNode to get a reference to the parent node. Then you can get its ID with .id. So alert(this.parentNode.id) should work.

<div id="one">
    <p>Some Text</p>
    <img src="http://placehold.it/48x48" alt="" id="two" onclick="random(this)" />
</div>
    
<script>
    function random(node) {
        alert("working" + " " + node.parentNode.id);
    }
</script>