Reputation: 464
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?
Upvotes: 4
Views: 1099
Reputation: 860
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.
Upvotes: 0
Reputation: 464
I have put together a basic feature test for those that run across this in the future.
https://codepen.io/freemagee/pen/QgoNJz
Basically a SVG is dynamically created and the dataset is manipulated in a 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 am not smart enough to do a proper polyfill, but this took a site that failed in Microsoft Edge to fully working.
Upvotes: 1