I’ve just lost my whole morning to what should have been a very basic and straightforward task. Sorry if the solution to this problem is obvious to you, I’m beginning on D3.js and Javascript.
I’m looking to load, in D3, an external svg file, and have it as an inline svg to do further operations, not as a static image, and working on local files. I don’t understand how there couldn’t be a way to do such a simple and basic thing. I’ve tried anything I could:
- Using this library: https://github.com/iconfu/svg-inject . This library promises to do the exact thing I want to do. However their basic examples (Basic usage section) give me static images, and not inline svg as promised (with Firefox 98.0), so I can’t use it.
- I tried the example here: http://www.zevross.com/blog/2019/08/20/load-external-svgs-with-d3-v5/ (section “Get the XML data / Load one illustration, one time”) with a local svg, it just renders a blank window; “Inspect Element” shows nothing was loaded
- Solutions such as the accepted one on this post (How to access SVG elements with Javascript) are not helpful either, as not working on local files
- A call to d3.xml (https://bl.ocks.org/mbostock/1014829) proved to be completely useless too, as it doesn’t render anything :
<!DOCTYPE html>
<html>
<head>
<script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
<script>
d3.xml('nameOfMysvgFile.svg')
.then(data => {
document.body.append(data.documentElement)
})
</script>
</body>
</html>
So far the best I achieved was to load my svg as an object (as done here: http://dahlström.net/svg/html/get-embedded-svg-document-script.html), and then I’m stuck, as I can’t do any operation in Javascript on that object. How to transfer the contents of the object to inline svg? Or how to take out that #document “wrapping” that prevents from doing anything on the svg? Or even better, add the contents to an existing svg container (mySvgContainer.append("g").[magic command to add the contents of external svg file]
)?