Alternative approach to handle click events (performance related)

I found a javascript tutorial in which a coder seems to handle click events by an alternative approach.

  1. Place an eventlistener for clicks on the body
  2. Give all elements inside the body a specific data-element attribute (additional data-attributes may be required to specify the exact element)
  3. Place a switch inside of the body-eventlistener and let it check for e.target.dataset.element
  4. Execute code based on the data-element attribute

This can look like this (simplified):

document.addEventListener("DOMContentLoaded", () => {
    document.body.addEventListener("click", e => {
        e.preventDefault();
        switch (e.target.dataset.element) {
          case "navigation":
                console.log("a navbutton was clicked")
          case "something":
                console.log("something was clicked")
        }
    });
});

Do you think this can lead to better performance? No more than 1 eventlistener for clicks are neccessary by this approach. There is even space for other improvements like no need for the usage of buttons (p tags could handle things), and so, and so…

Love to get your opinion to it.

Best regards

Event delegation is a useful pattern. For example, on a parent container with a lot of elements inside that all otherwise would need event handlers.

But I don’t particularly know if I like the idea of only having one listener on the document and doing everything through delegation. Doing it purely as some sort of (premature) optimization is probably not the right choice. I’m also not sure if it actually is an optimization considering any time you click anywhere on the document the event fires and you have to run the delegation logic. The idea that just clicking the document anywhere will cause code to run also just feels a bit wrong to me.

If you want a button then you should use a button element (semantics and accessibility).