最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - d3 how to insert new SVG element before existing other element? - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

1 Answer 1

Reset to default 5

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/d3.v4.min.js"></script>

发布评论

评论列表(0)

  1. 暂无评论