Reputation: 21437
Thanks to this question I think I learnt how to do this but I can't quite believe I've got it right as it's ugly as you like.
Let's say there's an element #foo
and I want to create an SVG
element before it. Do I really have to do this:
var svg = d3.select(d3.select('#foo').node().parentNode)
.insert('svg', '#foo')
Am I missing something? (EDIT: to be clear, the sample code above does work, but it's pretty opaque and includes repetition of the selector.)
Upvotes: 2
Views: 7617
Reputation: 102218
You just need the type
and the selector
:
selection.insert(type, before)
For instance, in this demo, the circle is an element with ID foo
. So,
var svg2 = svg.insert("svg", "#foo");
Inserts a child SVG before the circle element.
var svg = d3.select("body").append("svg")
var circle = svg.append("circle").attr("id", "foo");
var svg2 = svg.insert("svg", "#foo");
svg2.attr("id", "childSVG");
var mySVG = (new XMLSerializer()).serializeToString(svg.node());
console.log(mySVG)
<script src="https://d3js.org/d3.v4.min.js"></script>
Upvotes: 5