I have the following SVG inline on my website:
<svg xmlns="http://www.w3.org/2000/svg" data-action="counter" class="button"
width="320" height="90" viewBox="0 0 320 90">
<rect x="0" y="0" width="320" height="82" rx="10" ry="10" fill="#114477" />
<text alignment-baseline="central" text-anchor="middle"
x="160" y="41" font-size="48" fill="#c1cedb">Botón</text>
</svg>
I want that, no matter where the user clicks on the SVG, a function that controls the event is launched and for that I have the following JavaScript:
document.querySelector(".button").addEventListener("click", function() {
console.log(this.dataset.action);
});
The problem is that it always seems to return an error because JavaScript says that dataset
is not defined for the selected element:
document.querySelector(".button").addEventListener("click", function() {
console.log(this.dataset.action);
});
<svg xmlns="http://www.w3.org/2000/svg" data-action="counter" class="button"
width="320" height="90" viewBox="0 0 320 90">
<rect x="0" y="0" width="320" height="82" rx="10" ry="10" fill="#114477" />
<text x="160" y="41" alignment-baseline="central" text-anchor="middle" font-size="48" fill="#c1cedb">Botón</text>
</svg>
The same code but for another HTML element (eg a div
) works without problems. I tried to move the attribute data-action
to rect
(changing the selector) but I get the same error. What is wrong? How can I select a data attribute in SVG from JavaScript?