Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use d3 to generate markup but not manipulate the DOM?

Given the following code, I can append an svg circle to a body tag.

d3.select("body")
  .append("svg")
  .append("circle")
    .attr("cx", 30)
    .attr("cy", 30)
    .attr("r", 20);

But say I want to use d3 to just generate the markup:

<svg><circle cx="30" cy="30" r="20"/></svg>

and assign it to a javascript variable to eventually be rendered on the page. In this case I don't want d3 to directly manipulate the DOM, but I want to use its magic to generate my markup.

How do I go about this.

like image 337
dbj44 Avatar asked Nov 19 '25 08:11

dbj44


1 Answers

You could use a lightweight DocumentFragment to create an in-memory tree which is not part of the actual DOM tree. Because the DocumentFragment interface inherits from the Node interface you could easily wrap it in a D3 selection and do your normal D3 operations starting from the new virtual root. When finished the desired source string can be obtained from the outerHTML property of the root node, i.e. your appended <svg>.

// Create a document fragment in memory and wrap a D3 selection around it.
var doc = d3.select(document.createDocumentFragment());

// Do your normal D3 stuff.
var svg = doc.append("svg")
svg.append("circle")
  .attr("cx", 30)
  .attr("cy", 30)
  .attr("r", 20);

// 1. Obtain your source string from the outerHTML property.
var svgString = svg.node().outerHTML;
console.dir(svgString);

// 2. You can run a normal selection on the root
// This variant does not even require keeping a
// reference to the appended elements.
svgString = doc.select("svg").node().outerHTML;
console.dir(svgString);
<script src="https://d3js.org/d3.v4.js"></script>

Note: As I just realized, there is one drawback, though, since IE still does not support innerHTML or outerHTML properties for SVG content. Therefore, this approach is no viable solution if you need to support IE.

like image 200
altocumulus Avatar answered Nov 21 '25 21:11

altocumulus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!