Sure, here's a suggestion on how you could frame your question for Stack Overflow:
Title: Event delegation not working as expected when trying to remove elements in JavaScript
Body:
I'm trying to use event delegation in JavaScript to handle click events on elements that are dynamically added to the DOM. I have a container element with the class "experience-cont", and inside this container, there are elements with the class "garbage-btn". I'm trying to set up an event listener so that when a "garbage-btn" is clicked, its grandparent element is removed from the DOM.
Here's the JavaScript code I'm using:
let experienceCont = document.getElementsByClassName("experience-cont")[0];
let resultCont = document.getElementById("experienceResult");
experienceCont.addEventListener("click", (e) => {
if(e.target && e.target.classList.contains("garbage-btn")){
let removeEle = e.target.parentNode.parentNode;
console.log("remove");
resultCont.removeChild(removeEle);
}
else if(e.target && e.target.value === "Add"){
let ele = document.getElementsByClassName("hidden")[0];
console.log("add");
resultCont.appendChild(ele.cloneNode(true));
}
});
And here's the relevant part of my HTML:
<div class="form-cont experience-cont accordion-cont">
<div class="static-form-cont">
<div class="title-cont"><span class="text">Experience</span></div>
<div class="accordion-btn"><img src="../arrow-down-sign-to-navigate.png" alt="arrown btn"></div>
</div>
<label><input type="submit" value="Add" id="experienceBtn"></label>
<div class="experience-result" id="experienceResult">
<div class="hidden">
<div class="static-form-cont">
<div class="garbage-btn"><img src="../trash.png" alt="delete btn"></div>
<div class="title-cont"><span class="text"></span></div>
<div class="accordion-btn"><img src="../arrow-down-sign-to-navigate.png" alt="arrown btn"></div>
</div>
<!-- More HTML here... -->
</div>
</div>
</div>
The problem is that the "garbage-btn" click event is not working as expected. When I click a "garbage-btn", I expect its grandparent element to be removed from the DOM, but this is not happening. There are no error messages in the console, and I've confirmed that the event listener is being triggered when a "garbage-btn" is clicked.
I've tried using both removeChild() and remove() to remove the element, but neither is working. I've also tried attaching the event listener to different elements and using different methods to select the element to be removed, but nothing has solved the issue.
Does anyone know what could be causing this issue and how I can fix it?
Edit --- The problem was with where event should be clicked. i was clicking img inside of garbage btn so i just moved the class from div to img.
it not working because click target on img tag, and it not have class "garbage-btn", you can try click outside image, element will removed
you can using icon instead of image, or add event onclick in img tag to fix this