Is there a way to just generate an svg and get it as a string without actually drawing it? I thought about render svg to a hidden div and then reading the inner html, but is there a cleaner way?Answer1:
I would think you could do this:
var svg = d3.select("body").append("svg") svg = d3.select(svg).remove()
Append the svg to the body, but immediately remove it. This will, of course, give you the 'd3 selection' object, not a string.Answer2:
createDocumentFragment()</a>. This is commonly used to create a complex section of the document and then add it all to the page in one step, so the browser only has to re-calculate layout once.
I haven't tested it, but you should also be able to use
.innerHTML() to extract everything you've created as a string that can be saved to file. Answers to <a href="https://stackoverflow.com/questions/1750815/get-the-string-representation-of-a-dom-node" rel="nofollow">this SO Question</a> suggest that you can't call
innerHTML() directly on the document fragment itself, so you would have to add a body element to the fragment, add your SVG to it, and then get the inner HTML from the body node.
One way to approach this problem is by checking how it would be done on the server side -- where there is no DOM.
As it turns out, the <a href="https://bl.ocks.org/tomgp/c99a699587b5c5465228" rel="nofollow">way to do this on the server side</a> involves more or less the same "hack" used in the question. This is because d3 expects to work on a DOM; writing that DOM to HTML is really the only way to render it to a string.
var svg = window.d3.select('body') .append('div').attr('class','container') .append('svg'); // and lots of other stuff //etc etc svg.selectAll('.arc').doSomething('blah blah'); var svgAsString = d3.select('.container').html();