GoMega54 GoMega54 - 2 months ago 8
HTML Question

target parent div ID with event hander

Is it possible to target the ID of a parent div with an even handler in an HTML file? Given the following code, when you click the image an alert fires containing the ID of the image "two". Is it possible to make "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>

Comments