I am encountering an issue with a function that switches between two colors when an element is clicked. The function works correctly on the parent element, but not on the child element. Can you help me understand why?
<div class="parent red">
<div class="child blue"></div>
</div>
<script scr="text/javascript" defer>
let parent=document.getElementsByClassName("parent")[0];
let child= document.getElementsByClassName("child")[0];
function toggleColor(e){
let background= e.target.classList;
console.log(e.target);
console.log("event fired")
if(background.contains("blue")){
e.target.classList.remove("blue");
e.target.classList.add("red");
console.log("event fired")
}
else if(background.contains("red")){
e.target.classList.remove("red");
e.target.classList.add("blue");
console.log("event fired")
}
}
parent.addEventListener("click",toggleColor,false);
child.addEventListener("click", toggleColor,false);
</script>