duplicates while loading external svg

Hello,
I’m pretty new here and in d3 in general. Trying to embed external SVG into my notebook (something like https://observablehq.com/@saradelessio/load-external-svg-with-d3). The problem is when i run the cell more than once i get duplicate.
How to do it properly?
Thank you

Welcome @shakraz!

Here are two approaches (depending on what your real code looks like, there may even be others that work better – if you share your notebook we can help more):

  1. combine the target div and the SVG loading cell into one
  2. remove all children from the target div before appending the SVG again

In both examples, I replaced d3.select(...).node() with a direct reference to the DOM element. See part 4 of this notebook:

1 Like

Thank you so much @bgchen! It works!

If you only want to display the SVG you can also use an <img> element:

html`<img src="https://s3.amazonaws.com/files.zevross.org/blog/d3_external_svgs/load_svg/leaves/maple_illustration.svg">`

In some cases you might also need to add a crossorigin=anonymous attribute.

1 Like