How to make an svg interactive to gather comments/annotations on depicted elements

I create directed graphs like the following from wikidata with the help of networkx and nxv. The result is an svg file which might be embedded in some html page.

wikidata digraph

Now I want that every node and every edge is “clickable”, such that a user can add their comments to specific elements of the graph. I think this could be done with a modal dialog popping up. This dialog should know from which element it was triggered and it should send the content of the textarea to some url via a post request.

What would be the best way to achieve this?


Wrapped in a W3C standard Web Component (supported in all Modern Browsers) you can make it generic for any src="filename.svg"

<graphviz-svg-annotator src="fsm.svg"></graphviz-svg-annotator>
<graphviz-svg-annotator src="Linux_kernel_diagram.svg"></graphviz-svg-annotator>
  svg .annotate { cursor:pointer }
  customElements.define('graphviz-svg-annotator', class extends HTMLElement {
    constructor() {
      let loadSVG = async ( src , container = this.shadowRoot ) => {
        container.innerHTML = `<style>:host { display:inline-block }
                               ::slotted(svg)  { width:100%;height:200px }
                               <slot name="svgonly">Loading ${src}</slot>`;
        this.innerHTML = await(await fetch(src)).text(); // load full XML in lightDOM
        let svg = this.querySelector("svg");
        svg.slot = "svgonly"; // show only SVG part in shadowDOM slot
        svg.querySelectorAll('g[id*="node"],g[id*="edge"]').forEach(g => {
          let label  = g.querySelector("text")?.innerHTML || "No label";
          let shapes = g.querySelectorAll("*:not(title):not(text)");
          let fill   = (color = "none") => shapes.forEach(x => = color);
          let prompt = "Please annotate: ID: " + + " label: " + label; 
          g.onmouseenter = evt => fill("lightgreen");
          g.onmouseleave = evt => fill();
          g.onclick = evt => g.setAttribute("annotation", window.prompt(prompt));
      super().attachShadow({ mode: 'open' });


  • this.innerHTML = ... injects the full XML in the component ligthDOM
    (because the element has shadowDOM, the lightDOM is not visible in the Browser)

  • But you only want the SVG part (graphviz XML has too much data)… and you don’t want a screen flash; that is why I put the XML .. invisible.. in lightDOM

  • A shadowDOM <slot> is used to only reflect the <svg>

  • with this method the <svg> can still be styled from global CSS (see cursor:pointer)

  • With multiple SVGs on screen <g> ID values could conflict.
    The complete SVG can be moved to shadowDOM with:

     let svg = container.appendChild( this.querySelector("svg") );

    But then you can’t style the SVG with global CSS any more, because global CSS can’t style shadowDOM