So, I was writing some JS for a little task-app I'm making, and I noticed something very strange with the Event.target.closest() method.
So, I did some testing, and I realized something extremely dumb.
If you have more than one target.closest within scope of each other, the second one will break for seemingly no reason, returning null
as if the selected element class didn't exist. Why this happens? No idea! It's not listed anywhere I can find it as an error and it wasn't listed as a potential limitation on Mozilla's webdocs.
If you don't believe me; here's the code I used to test it; (no, neither it being in a function or it being outside of the eventlistener does anything!)
const btn1 = document.getElementById('btncontainer')
btncontainer.addEventListener("click", Event => {
return Event;
})
window.onload() = (event) => {
function click(e) {
const btn1 = e.target.closest('btn1')
const btn2 = e.target.closest('btn2')
if (btn1) {
console.log("hi")
} else if (btn2) {
console.log("bye")
}
}
click(Event)
}
I'm making this post to save any potential people like me the time and headache of realizing that this jankery happens! This cost me a solid half-hour before I tested it and realized that I, in-fact, was not the problem.