Accepted answer

I have no good reason why .selectAll('xhtml:td') is not working may be this is not supported.

But i tried the following and it worked thought of sharing with you:

var table = svg.append("foreignObject")
  .attr("width", 480)
  .attr("height", 500)
  .append("xhtml:body")//append body to foreign object(this is missing in your code) 

Then you can simply append elements as you used to do in d3 like below.

  // append header row
  .selectAll('th')//select using normal selector without xhtml

Working code here

Hope this helps!

Related Query

More Query from same tag