14

Instead of doing

d3.select("body").append("svg")

, which most d3.js examples do, I'd like to create an element, and NOT attach it to body or anything right away.

Kind of like $('<div/>') in jQuery.

How can I do this?

user1527166
  • 3,229
  • 5
  • 26
  • 26
  • 1
    possible duplicate of [How to create "svg" object without appending it?](http://stackoverflow.com/questions/18455282/how-to-create-svg-object-without-appending-it) –  May 29 '15 at 19:19

5 Answers5

22

Create the element using document.createElement() and pass it to d3 as usual.

In console:

> a = document.createElement("div")
<div>​</div>​
> d3.select(a).append("svg")
[Array[1]]   
> a
<div>​
<svg>​</svg>​
</div>​
minikomi
  • 8,363
  • 3
  • 44
  • 51
9
// create selection containing unattached div node    
var sel = d3.create('svg');  

and if you want just the node...

// retrieve unattached node
var node = d3.create('svg').node();
eric.mcgregor
  • 3,507
  • 2
  • 16
  • 16
2

To create the svg element "in memory" use document.createElementNS.

Use of document.createElementNS:

// Create the svg elem
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");

// Create a g elem
var g = document.createElementNS("http://www.w3.org/2000/svg", "g");

// Create a d3 Selection with the elem
var d3Svg = d3.select(svg);
var d3g = d3.select(g);

Append a d3 selection to another d3 selection:

d3Svg.append(function(){ return d3g.node(); });
borracciaBlu
  • 4,017
  • 3
  • 33
  • 41
1

You should try something like:

var $svg = $('<svg/>');
var d3svg = d3.select($svg[0]);

// ... manipulate d3svg ...

$('body').append($svg)

Hope it helps.

Pedro
  • 164
  • 1
  • 4
0

I had to do this in order to support percentage widths on my custom SVG element:

var svgDom = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svgDom.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink");
svg = d3.select(svgDom)
    .attr("class", "chart")
    .attr("width", "100%")
    .attr("height", "100%");
skibulk
  • 3,088
  • 1
  • 34
  • 42