Why can't I add a graph to a dynamically inserted svg element?

271 views Asked by At

I have a simplistic graph as follows:

var g = new dagreD3.graphlib.Graph().setGraph({});
g.setNode(0, { label: "Zero"});
g.setNode(1, { label: "One"});
g.setEdge(0, 1, { label: "Edge"})

var render = new dagreD3.render();
var svg = d3.select("svg"),
    svgGroup = svg.append("g");
render(d3.select("svg g"), g);
.node rect {
  stroke: black;
  fill: white;
}

.edgePath path {
  stroke: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<script src="https://dagrejs.github.io/project/dagre-d3/latest/dagre-d3.min.js"></script>

<div id="svgwrapper">
    <svg id="svg-canvas" width=960 height=600></svg>
</div>

But must the svg element be hard-coded in the HTML code, as above? Can I not insert it dynamically?

Now I don't know how do d3 and dagre function under the hood, however, to my understanding I shouldn't have to! This is because when I call this:

var svgg = document.createElement('svg');
document.getElementById('svgwrapper').appendChild(svgg);
svgg.width = "960";
svgg.height = "600";
svgg.id = "svg-canvas";

As soon as the above code completes its execution, (to my understanding) an svg element is inserted to the document, and an identical one to the one hardcoded in the HTML code... so from now on there should be no difference for any subsequently-executing JS code between the two situations?

Yet this is not the case. Even though I'm inserting the svg element before constructing and (trying to) insert the graph, this fails:

var svgg = document.createElement('svg');
document.getElementById('svgwrapper').appendChild(svgg);
svgg.width = "960";
svgg.height = "600";
svgg.id = "svg-canvas";

var g = new dagreD3.graphlib.Graph().setGraph({});
g.setNode(0, { label: "Zero"});
g.setNode(1, { label: "One"});
g.setEdge(0, 1, { label: "Edge"})

var render = new dagreD3.render();
var svg = d3.select("svg"),
    svgGroup = svg.append("g");
render(d3.select("svg g"), g);
.node rect {
  stroke: black;
  fill: white;
}

.edgePath path {
  stroke: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<script src="https://dagrejs.github.io/project/dagre-d3/latest/dagre-d3.min.js"></script>

<div id="svgwrapper">
</div>

What am I doing wrong? How can I insert a graph to a dynamically constructed svg element?

0

There are 0 answers