Is there any way to append a foreignObject
element containing some simple HTML to an svg element? Here's the code I tried:
var foreignObject = document.createElement('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
But the svg remains the same even after this code executes. Is there anything else that I need to do?
SVG images can be written directly into the HTML document using the <svg> </svg> tag. To do this, open the SVG image in VS code or your preferred IDE, copy the code, and paste it inside the <body> element in your HTML document. If you did everything correctly, your webpage should look exactly like the demo below.
This can be solved by using the <foreignObject> SVG element in which you can add an HTML under a different namespace than the parent SVG and then you can also style the elements using CSS like so.
SVG supports embedded content with the use of 'image' and 'foreignObject' elements. Additionally SVG allows embedded content using HTML 'video', 'audio', 'iframe' and 'canvas' elements.
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With