Get the parent's id in JavaScript

Let's assume that you have the following HTML structure:

HTML
<div class = 'Parent' id = 1 onclick = 'getParentId(event)'>
    <div class = 'Child'>Hi</div>
    <div class = 'Child'>Bye</div>
</div>

Use e.target.parentElement.id to get the parent's id after clicking on one child.

Example:

javascript
function getParentId(e){

    // Printing the parent's id "1"
    console.log(e.target.parentElement.id)

    // If you try to use the following
    // console.log(e.target.id)
    // If you click on one child, you'll print ""

}

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.