Select data-attribute within SVG

2

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?

    
asked by Alvaro Montoro 23.08.2016 в 13:23
source

1 answer

2

You're right, it only worked for me in (Mac) Safari Release 11 (Safari 9.1.2, WebKit 11603.1.2) but in Chrome Version 52.0.2743.116 (64-bit) no.

I think the solution is to use getAttributeNS , I've never used it but I'm sure that the document clarifies things a lot.

document.querySelector(".button").addEventListener("click", function(event) {
    console.log(event.currentTarget.getAttributeNS(null, 'data-action', null));
})

I have edited the example so you can see what works.

    
answered by 23.08.2016 / 14:24
source