Let's say I create a simple graphic like this:
<!doctype html>
<html lang="en">
<head>
<script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<svg></svg>
<script>
const svg = d3.select('svg');
const g = svg.append('g');
g.append('g')
.selectAll('g')
.data([5, 10, 20, 40])
.enter()
.append('rect')
.attr('fill', 'green')
.attr('x', d => d)
.attr('y', d => d)
.attr('height', d => d)
.attr('width', d => d);
</script>
</body>
</html>
But instead of just appending to it, I want to create a detached <g>
which can then be appended at will (e.g. it could be returned from a function).
With d3 V5 there is a d3.create()
function which creates a detached element.
<!doctype html>
<html lang="en">
<head>
<script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<svg></svg>
<script>
const svg = d3.select('svg');
const g = svg.append('g');
const detachedG = d3.create('g');
detachedG.selectAll('g')
.data([5, 10, 20, 40])
.enter()
.append('rect')
.attr('fill', 'green')
.attr('x', d => d)
.attr('y', d => d)
.attr('height', d => d)
.attr('width', d => d);
g.append(() => detachedG.node());
</script>
</body>
</html>
But it doesn't appear in the browser, even though the DOM looks the same.
Any ideas how to fix this?