JSFiddle - React, Tailwind, and code Playground
HTML
<p>I am a simple html text content, and here is a simple svg <rect> that should be red: <svg width="50" height="50"><rect x="0" y="0" height="50" width="50" fill="red"/></svg></p>
CSS
iframe.svg-viewer {
border: none;
}
JavaScript
const svg = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="500" height="200">
<style>
:root {
font: 40px Serif;
}
rect {
fill: green;
}
</style>
<text y="50">I'm a big text in an svg image.</text>
<rect id="myrect" x="25" y="75" width="50" height="50"/>
</svg>`;
/*
// here we are assuming
fetch(url)
.then(resp => resp.blob())
.then(blob => appendSVGDoc(blob, document.body));
*/
const blob = new Blob([svg], {type: 'image/svg+xml'});
appendSVGDoc(blob, document.body)
.then(svgdoc => {
svgdoc.querySelector('text').textContent = 'We still can modify it';
}).catch(console.error);
// and we can even append an other one
appendSVGDoc(blob, document.body)
.then(svgdoc => {
// with no conflict in ids anymore
svgdoc.getElementById('myrect').setAttribute('height', 100);
}).catch(console.error);
function appendSVGDoc(blob, parent) {
return new Promise((res, rej) => {
const url = URL.createObjectURL(blob);
const iframe = document.createElement('iframe');
iframe.classList.add('svg-viewer');
iframe.onload = e => {
const doc = iframe.contentDocument;
const docEl = doc.documentElement;
// iframe doesn't auto size like <object> would
iframe.width = docEl.getAttribute('width') || '100%';
iframe.height = docEl.getAttribute('height') || '100%';
res(doc);
};
iframe.onerror = rej;
iframe.src = url;
parent.appendChild(iframe);
});
}