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.)
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.)
Share Improve this question edited May 23, 2017 at 11:53 CommunityBot 11 silver badge asked Nov 16, 2016 at 12:24 artfulrobotartfulrobot 21.5k12 gold badges61 silver badges91 bronze badges1 Answer
Reset to default 5You 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/d3.v4.min.js"></script>