Problem with event.target.parentElement

Hi everyone,

I’m trying to change the color of an icon using JavaScript onclick event, however, for some reason the code doesn’t select it properly.

I was trying to console log the event.target (for testing) and when I run console.log(event.target) it returns properly the <i> element, but when I run console.log(event.target.parentElement) I would expect it to return div but instead it returns null. I don’t understand why - the icon is wrapped in the div so the div should be its parent element as far as I understand. Because of that I can’t do much with the styling. What am I missing here?

I have the following HTML code:

<div class="completed"> <i class="far fa-circle"></i> </div>

Then the following JS (only snippet):

else if (event.target.parentElement.classList.contains('completed')) {
        event.target.parentElement.innerHTML = '<i class="far fa-check-circle"></i>';
        console.log(event.target) //returns <i>

//this part is not working
        event.target.style.color = "green"; // doesn't change the color
        console.log(event.target.parentElement) //returns null
    }

Thank you!

You’ve removed the thing you are trying to change, it doesn’t exist any more so there is no event.target: you replaced it with the i with the checkmark.

Just change the class, you don’t need to delete it

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.