Another short one! Let's talk about the two HTML helper methods, Element.matches and Element.closest. Both of these methods are supported in modern...
For further actions, you may consider blocking this person and/or reporting abuse
Good post!
And if you need to support IE11, the polyfill is very light. You can find examples on the MDN pages:
Or you can just use Babel.
Babel on its own is not a magic bullet—you need to include the right polyfill with it, since it's not a language feature. But your point is valid and the polyfills are easy.
IE11 is ~2%, for me on any modern content site, I just don't ship it any JS whatsoever. This is what we did for e.g. the Chrome Dev Summit site.
Yeah you need to include the Babel polyfill properly.
Haha, I'm jealous. Unfortunately the website I'm working on is B2B focused which has a significant number of enterprise users in IE11. Ah well.
Babel doesn't polyfill DOM methods.
I lost 3 days on this and ended with
npm i --save-dev element-closest-polyfill
import 'element-closest-polyfill'
:(, sorry you lost days on this. Yeah in my experience polyfill issues are tricky to debug. You're right, Babel needs a polyfill for DOM methods.
element-closest-polyfill
seems to do the job well.In the future, if you want to polyfill a lot of stuff automatically, Babel recommends using core-js and regenerator-runtime/runtime. (It mentions it at the top of the page for the deprecated babel/polyfill). However, those can be a lot of work and configuration, so specific polyfills like
element-closest-polyfill
are very good.Hi, thanks for your reply.
I looked for a regenerator-runtime/runtime config with Rollup and Babel.
Didn't find so I ended up with temporary element-closest-polyfill.
Thanks for your answer.
Just a nitpick:
The following line:
el.classList.has('foo') /* becomes */ el.matches('.foo');
I think you mean 'contains' instead of 'has'
Oh yeah, I think I was thinking of
Set
orMap
. I'll fix, thanks! 👍I used
closest
to refactor some recursive code recently! It's a super cool method. I didn't know about matches though -- so thanks 😊How are you finding daily code blogging?
Matches is probably less useful but is really a precursor to
closest
.Daily blogging is going well but—having a newborn is complex, we've lots of medical appointments—so I've slipped a bit so I'm now making each post about ~2 hours before my artificially self-imposed deadline (midnight on the day, in Sydney time).
I have a remarkably large short list of topics that I'd like to blog about, so I'm not low on ideas. I just need to build up a buffer again 🤣
Oh, very cool! I knew about
.matches()
, but I didn't know that we had.closest()
as well. This is perfect for any kind of event-delegation. About time!Really interesting!
Nice tip Sam! Keep up the good work!