TIL about the element.closest() method
POSTED ON:
TAGS: javascript codepen eventlisteners
You create a button and the event listener for that button:
<button class="click-me">
<span class="text-large">Click Me!</span>
<br>
<span class="text-small">(limited time offer)</span>
</button>
<script>
document.addEventListener('click', function (event) {
// Only run on .click-me buttons
if (!event.target.matches('.click-me')) return;
// Do stuff...
});
</script>
Right now, it LOOKS like the code will work. If the button has a .click-me
, then it should work, right?
Well, your click events are ACTUALLY happening on those span
elements.
See the Pen Event Delegation by Chris Ferdinandi (@cferdinandi) on CodePen.
To get around that, we use the element.closest()
trick.
document.addEventListener('click', function (event) {
// Only run on .click-me buttons
if (!event.target.closest('.click-me')) return;
// Do stuff...
});
Our click events that happen in span
now check if the nearest element contains .click-me
, which is TRUE!
See the Pen Event Delegation - Fixed by Chris Ferdinandi (@cferdinandi) on CodePen.
via Climbing up the DOM tree with vanilla JavaScript
Related TILs
Tagged: javascript