Search code examples
javascripthtmlsvginternet-explorer-11microsoft-edge

Microsoft Edge can not set data attribute on SVG


Just run into something I did not expect. Testing a site in IE Edge, I get an error in the console:

Unable to set property 'shape' of undefined or null reference

After debugging for a while it seems that Microsoft Edge can not set a data attribute on an SVG element using dataset. I made a reduced test case:

https://codepen.io/freemagee/pen/YQRowd

There is a single SVG on that Codepen, which I then try to add some data attributes to it using dataset. When I view that codepen in Microsoft Edge I get the console error.

Codepen snippets

HTML

<svg version="1.1" id="svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
     width="50px" height="50px" viewBox="0 0 50 50">
  <rect id="square" width="50" height="50" stroke="red" stroke-width="2px" fill="transparent" />
</svg>

JS

function setSvgData() {
  var svg = document.getElementById('svg');

  svg.dataset.shape = 'square';
  svg.dataset.emotion = 'gloomy';
}

setSvgData();

Having read up on SVGElement.dataset I am unsure what to do now to resolve this. I would like to avoid having to rewrite all my dataset code with setAttribute if possible.

Anyone experienced this or know how to resolve it?


Solution

  • There is an issue for it with the status of 'Fixed, Not yet flighted' here: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8489259/

    In the meantime, and for backwards compatibility, using getAttribute and setAttribute instead of dataset seems to be the way to go.