liveBook · Manning

foreignObject

As explained in D3.js in Action, Third Edition

An SVG foreignObject element embeds non-SVG content, such as HTML elements, within an SVG document.

foreignObject embeds regular HTML elements inside an SVG container. A nested div brings automatic text wrapping to visualization labels, avoiding the extra work required for multiline SVG text. section 11.2.3

Use foreignObject labels by:

  • Appending foreignObject elements through D3 data binding. section 11.2.3
  • Setting width, height, x, and y to align the HTML region with its circle. section 11.2.3
  • Appending an xhtml:div inside each foreignObject and styling or populating it like ordinary HTML. section 11.2.3

How D3.js in Action, Third Edition covers it

How deep it goes
Explains the element, required geometry attributes, namespace, and D3 construction, but stops short of broader browser behavior.
Examples
Uses language labels in a circle-pack visualization, including names such as Modern Standard Arabic and Western Punjabi.
What it assumes
Assumes an SVG container and D3 data binding while teaching the HTML-inside-SVG pattern directly.
What you can do after
Build multiline HTML labels inside SVG visualizations and align them with data-driven shapes.
How it connects
Connects SVG, HTML, D3 data binding, multiline text, and mouse events.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of D3.js in Action, Third Edition. The section links point to the parts of the book it draws on.