简体   繁体   中英

d3 how to insert new SVG element before existing other element?

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.)

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM