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?
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?
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>
// 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();
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(); });
You should try something like:
var $svg = $('<svg/>');
var d3svg = d3.select($svg[0]);
// ... manipulate d3svg ...
$('body').append($svg)
Hope it helps.
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%");