Home > Mobile >  finding the id of the parent element
finding the id of the parent element

Time:09-26

I'm trying to access the id of the parent of my event, but it is not working right now.

Here is my code :

const deleteComment = (event) => {
    checkId = event.target.id;
    parentEvent = event.target.parentNode;
    parentEventId = event.target.parentEvent.id; // return "Cannot read properties of undefined (reading 'id')" in console
    console.log('parentEventId:', checkId);
    console.log('parentEvent:', parentEvent); 

    //delete all of what is inside the parent;
    parentEvent.innerHTML= "";

would you have a solution for me to check the id of this parent, or just erase the parent (I've already find a way to erase what is inside the parent)

CodePudding user response:

You are using parentEvent attribute of target, which does not exist.

    parentEvent = event.target.parentNode;
    parentEventId = event.target.parentEvent.id;

Should be:

    parentEvent = event.target.parentNode;
    parentEventId = event.target.parentNode.id;

CodePudding user response:

const deleteComment = (event) => {
    const parentElement = event.target.parentElement
    const parentId = parentElement.id

    // delete all of what is inside the parent
    parentElement.innerHTML = "";

CodePudding user response:

This line of code you're using is the source of the issue parentEventId = event.target.parentEvent.id; // return "Cannot read properties of undefined (reading 'id')" in console

You're accessing the id on the event.target despite saving the parent in a separate variable above.

const deleteComment = (event) => {
    checkId = event.target.id;
    parentNode = event.target.parentElement;
    parentNodeId = parentNode.id; // will return the parent id
    console.log('parentNodeId:', checkId);
    console.log('parentNode:', parentNode); 

    //delete all of what is inside the parent;
    parentEvent.innerHTML= "";
  • Related