score:8

Accepted answer

You forgot to attach the namespace to the <foreignObject> Element:

var ns = 'http://www.w3.org/2000/svg';
var svg = document.querySelector( 'svg' );

var foreignObject = document.createElementNS( ns, 'foreignObject');
foreignObject.setAttribute('height', 300);
foreignObject.setAttribute('width', 300);

var div = document.createElement('div');
div.innerHTML = 'Hello World';

foreignObject.appendChild( div ); 
svg.appendChild(foreignObject); //svg is an already created svg element containing a d3 chart
<svg></svg>

score:10

You don't need document.createElementNS or document.createElement, you can simply append the foreignObject using your D3 selection.

This is an example borrowed from Bostock, D3 creator:

<meta charset="utf-8">
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var svg = d3.select("body").append("svg")
    .attr("width", 960)
    .attr("height", 500);
svg.append("foreignObject")
    .attr("width", 480)
    .attr("height", 500)
  .append("xhtml:div")
    .style("font", "14px 'Helvetica Neue'")
    .html("<h1>An HTML Foreign Object in SVG</h1><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eu enim quam. ");
</script>


Related Query

More Query from same tag