After receiving a recommendation from my colleagues on Stackoverflow (mplungjan, Michel), I implemented the event delegation pattern for a comment list. It has been working well and I am quite excited about this approach. However, I have encountered an issue with buttons that contain two child elements - spans.
The problem arises when I try to retrieve the CommentID from the parent element of the child element. This only works if the click happens exactly between the spans inside the button. Using currentTarget does not solve the issue as the tapped element is the entire comment list.
Question: What steps should I take to address this issue?
const commentList = document.querySelector('.comment-list');
commentList.addEventListener('click', (ev) => {
console.log('1. clicked');
const getObjectId = () => {
return ev.target.parentNode.parentNode.getAttribute('data-comment-id');
}
if (! getObjectId()) return false;
if (ev.target.classList.contains('delete')) {
console.log('2. Delete action');
console.log('3. for relatedID', getObjectId());
}
if (ev.target.classList.contains('edit')) {
console.log('2. Edit action');
console.log('3. for relatedID', getObjectId());
}
if (ev.target.classList.contains('flag')) {
console.log('2. Flag action');
console.log('3. for relatedID', getObjectId());
}
});
.controller {
display: flex;
gap:20px;
}
.comment {
margin-bottom: 20px;
background: gray;
}
.controller button > span {
background: orange;
}
.controller button span:first-child {
margin-right: 10px;
}
<div class="comment-list">
<div class="comment">
<div class="content">lorem 1. Dont work! Nested button.</div>
<div class="controller" data-comment-id="1">
<div class="delete">
<button class="delete"><span>delete</span><span>ICON</span></button>
</div>
<div class="edit">
<button class="edit"><span>edit</span><span>ICON</span></button>
</div>
<div class="flag">
<button class="flag"><span>flag</span><span>ICON</span></button>
</div>
</div>
</div>
<div class="comment">
<div class="content">lorem 2. Work! </div>
<div class="controller" data-comment-id="2">
<div class="delete"><button class="delete">delete</button></div>
<div class="edit"><button class="edit">edit</button></div>
<div class="flag"><button class="flag">flag</button></div>
</div>
</div>
<div class="comment">
<div class="content">lorem 3. Work! </div>
<div class="controller" data-comment-id="3">
<div class="delete"><button class="delete">delete</button></div>
<div class="edit"><button class="edit">edit</button></div>
<div class="flag"><button class="flag">flag</button></div>
</div>
</div>
</div>