Microsoft Edge cannot set data attribute in SVG

I'll just stumble upon something I didn't expect. Testing the site in IE Edge, I get an error in the console:

Can't set property 'shape' from undefined or null reference

After debugging for a while, it seems that Microsoft Edge is unable to set the data attribute on the SVG element using the dataset. I made a shortened test case:

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

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

Snippets of Codepen

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();

      

After reading SVGElement.dataset I'm not sure what to do now to solve this problem. I would like to avoid having to rewrite all of my dataset code with setAttribute if possible.

Has anyone experienced this or knows how to resolve it?

+3


source to share


2 answers


There is a "Fixed, Not yet flighted" status issue for it here: https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/8489259/



At the same time, for backward compatibility, using getAttribute

and setAttribute

instead is dataset

like the way to go.

0


source


I've put together a basic feature test for anyone working on this in the future.

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

Basically SVG is dynamically created and dataset is managed in try / catch.



var hasSvgDatasetSupport = supportSvgDataset();

function supportSvgDataset() {
  var doesSupport = true;
  var testSvg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');

  try {
    testSvg.dataset.shape = 'vector';
  } catch (error) {
    doesSupport = false;
  }

  return doesSupport;
}

// Example usage

var el = document.getElementById('shape');

if (hasSvgDatasetSupport) {
  el.dataset.mood = 'happy';
} else {
  el.setAttribute('data-mood', 'unhappy');
}

      

I'm not smart enough to do the right polyfill, but it took up a site that couldn't work completely in Microsoft Edge.

+1


source







All Articles