My parent container houses a variable number of elements generated by an API as the user inputs text. These elements, in turn, serve as parents to other child elements.
The goal is for an overlay with more details about a specific element to appear when the user clicks on it. Although this sounds straightforward, my attempts have been unsuccessful thus far.
I experimented with adding an event listener to the container using the following basic HTML template:
<ul>
<li><span>Item 1</span><span>X</span></li>
<li><span>Item 2</span><span>X</span></li>
<li><span>Item 3</span><span>X</span></li>
<li><span>Item 4</span><span>X</span></li>
</ul>
<form>
<input type="text" id="test">
</form>
In this example, the UL serves as the parent element with LI elements as its children. However, the LI elements also act as parents to essential span tags displaying crucial information, making their removal impossible. The input field allows dynamic additions to simulate the API's behavior.
Despite trying to attach an event listener to the UL parent >>
const items = ul.querySelectorAll('li');
items.forEach(item => item.addEventListener('click', function(e) {
console.log(this);
}));
});
});
I then attempted to add an event listener to each individual item but encountered a logging issue where clicking on one item would log multiple consecutive items. It feels like I am overlooking something crucial, and I am unsure of what that might be. Any assistance would be greatly appreciated!
Later edit: While I discovered a solution, it seems inelegant and susceptible to bugs if future changes are made (such as adding more children).
ul.addEventListener('click', e => {
const items = ul.querySelectorAll('li');
if(e.target.tagName === 'LI' || e.target.parentElement.tagName === 'LI') {
if(e.target.tagName === 'LI') {
e.target.remove();
} else if(e.target.parentElement.tagName === 'LI') {
e.target.parentElement.remove();
}
}
});