Accepted answer

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

var ns = '';
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


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">
<script src="//"></script>
var svg ="body").append("svg")
    .attr("width", 960)
    .attr("height", 500);
    .attr("width", 480)
    .attr("height", 500)
    .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. ");

Related Query

More Query from same tag