0

I have the following html and Javascript. I want to have a set of buttons with a single onclick handler.

    <div id="parent1">
        <button data-idx="1" data-action="test">Click me</button>
        <button data-idx="2" data-action="test">Click me</button>
    </div>
    <div id="parent2">
        <button data-idx="1" data-action="test"><span>Click me</span></button>
        <button data-idx="2" data-action="test"><span>Click me</span></button>
    </div>
    <script>
        const parent1 = document.querySelector("#parent1");
        const parent2 = document.querySelector("#parent2");
        parent1.addEventListener("click", (evt) => {
            let obj = evt.target.dataset;
            console.log(obj);
        });
        parent2.addEventListener("click", (evt) => {
            let obj = evt.path[1].dataset;
            console.log(obj);
        });
    </script>

The code for parent1 works fine and I see {idx:"1", action:"test"}

The code for parent2 works as well, but only because in this example I know in advance the structure of the innerHtml of the buttons. In practise that is not known, and the hard-coded evt.path[1] is not suitable.

It is the case however that the dataset is always in the immediate child of #parent2

How can I reliably find the dataset? For example, can I get the index relative to #parent of the child that fired the event?

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
Simon H
  • 19,279
  • 13
  • 64
  • 116

1 Answers1

1

Maybe you should use composedpath instead of path: see event.path is undefined running in Firefox.

In generall you can loop over the path[n] and avoid undefined errors.

Or you can access the different variables by using your above evt.target.dataset[keyname].

dawnb
  • 84
  • 3