Create an in-memory element, such as jQuery, in D3.js

Instead of doing

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

as most d3.js examples do, I would like to create an element and DO NOT attach it to the body or anything at once.

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

How can i do this?

+9
source share
5 answers

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

In the console:

 > a = document.createElement("div") <div>โ€‹</div>โ€‹ > d3.select(a).append("svg") [Array[1]] > a <div>โ€‹ <svg>โ€‹</svg>โ€‹ </div>โ€‹ 
+15
source

You should try something like:

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

Hope this helps.

+1
source

I had to do this in order to maintain the percentage width in 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%"); 
0
source

To create an svg element in memory, use document.createElementNS .

Using document.createElementNS:

 // Create the svg elem var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); // Create ag 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); 

Add d3 selection to another d3 selection:

 d3Svg.append(function(){ return d3g.node(); }); 
0
source
 // create selection containing unattached div node var sel = d3.create('div'); 

and if you want just a knot ...

 // retrieve unattached node var node = d3.create('div').node(); 
0
source

All Articles