Today I Learned - Rocky Kev

TIL about the element.closest() method

POSTED ON:

TAGS:

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:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.