block by biovisualize 373c6216b5634327099a

d3.selection.appendHTML and appendSVG

Full Screen

Parse and append an HTML or SVG string. I use it a lot for appending a template, instead of generating it with d3.

d3.select('.container').appendHTML('<div><svg><g><rect width="50" height="50" /></g></svg></div>');

Unlike using .html, .appendHTML can append multiple elements

d3.select('.container').html('<span id="a"></span>');
d3.select('.container').html('<span id="b"></span>'); // will replace content
d3.select('.container').appendHTML('<span id="c"></span>'); // will append content

You can append HTML or SVG using the right method

var svg = d3.select('.container')
    .appendHTML('<svg xmlns="http://www.w3.org/2000/svg"><g><circle class="circle1" cx="50" cy="50" r="50"></circle></g></svg>')
    .select('g');

svg.appendSVG('<circle class="circle2" cx="20" cy="20" r="20"></circle>');
svg.appendSVG('<rect width="30" height="30"></rect>');

And it can be used with the enter/update/exit pattern

d3.select('.container').selectAll('div.test')
    .data([0, 1, 2])
  .enter().appendHTML('<div class="test"><p></p></div>')
    .select('p')
    .text(function(d){ return d; });

index.html