66

I am trying to append an HTML div inside an SVG, which I am trying to create a graph. I am trying to append it using the code below, but when I inspect element using Firebug, the div is shown inside rect element code, but it doesn't show up in the graph UI.

Is it something wrong with the method that I am trying or is it impossible to append a div inside an SVG?

    marker.append("rect")
   .attr("width", "50px")
   .attr("height", "50px")
   .append("div")
   .attr("id", function(d) {
      return "canvas_" + d.key.split(" ").join("_");
   })
   .style("width", "50px").style("height", "50px");
ozil
  • 6,930
  • 9
  • 33
  • 56
sam
  • 2,277
  • 4
  • 18
  • 25

4 Answers4

81

You can't append HTML to SVG (technically you can with foreignObject, but it's a rabbit hole). Furthermore, visible elements in SVG can't be nested, so elements such as circle, rect, path and such can't have children elements.

methodofaction
  • 70,885
  • 21
  • 151
  • 164
  • 4
    Keep in mind `foreignObject` doesn't work in IE in case you need cross browser compatibility. – methodofaction Jul 11 '13 at 15:15
  • @sam Please consider accepting this answer if it solved your issue. I know the spec and I can verify that it is correct. – Benjamin Gruenbaum Jul 15 '13 at 12:09
  • 1
    Interesting! Too bad [IE didn't even try to support it](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/foreignObject#Browser_compatibility). Fun fact: **** shows up in SVGs saved from Adobe Illustrator when you tick the *Preserve Illustrator Editing Capabilities* option. – Mentalist Jan 17 '19 at 00:19
  • 1
    "*circle, rect, path and such can't have children elements.*" They can host non visible elements, such as for instance. – Kaiido May 03 '19 at 06:13
50

I would also consider using <g> element as it serves similar purpose as <div> by grouping objects. More about it here.

Karolis Ramanauskas
  • 1,045
  • 1
  • 9
  • 14
7

You are trying to append "rect" as well as "div" in the same line. Porbably that is where you are failing Check out these tutotials for D3... Its an amazing library based on SVG http://alignedleft.com/tutorials/d3/drawing-svgs/

AnaMaria
  • 3,520
  • 3
  • 19
  • 36
  • it didnt work with our rect either.. I just added rect coz I wanted to know if the append was wrking – sam Jul 11 '13 at 14:25
  • 3
    Check out those tutorials. I can promise you that you will learn much more than just SVG... – AnaMaria Jul 11 '13 at 14:26
0

If you work with HTML and SVG in the browser, a workaround can be to use the z-index. Instead of putting the HTML into the SVG, you can put the HTML over the SVG or the SVG over the HTML. I have used this technique to render an entity–relationship diagram in the browser. I have arranged my entities in HTML tables using absolute positions. And I have drawn the relations into the SVG. If you configure the SVG viewBox properly, you can use the same coordinates in your HTML and SVG.

ceving
  • 21,900
  • 13
  • 104
  • 178