1

So I have an svg sprite, which is not visible, that contains all the svg, and in the document it's just

<svg height="100" width="100"><use href="#mySvg"></use></svg>

to call an svg from the sprite.

The problem is the svg gets inside of shadow-root (closed), and I am not able to target individual parts of the svg with js.

I mean, I can target them, but just pointing at the original parts in the sprite, which translates to the svg called in the document, and that creates the problem cause I need to animate on hover, but this way, animating the orginal svg in the sprite, also animates every instance of that svg in the document, and not only the one with hover.

Is there something I am missing? Or is it simply not possible to make such manipulation using an svg sprite?

What alternative do I have if I need plenty of svg and can't put their inline code inside the document?

prastor159
  • 11
  • 2
  • ``use`` is a **reflection**, not a copy, of your ``#mySvg``. You can't change reflections. So using inline elements (copies) is one alternative. JavaScript ``cloneNode`` can create copies. – Danny '365CSI' Engelman Jun 18 '21 at 07:38
  • thanks, so what would be the best way to implement plenty of svg that will be individually manipulate? inline code for each of them is basically the only way? – prastor159 Jun 18 '21 at 10:00
  • See: https://stackoverflow.com/questions/66760400/what-is-the-best-practice-way-of-creating-an-icon-button-with-an-svg – Danny '365CSI' Engelman Jun 18 '21 at 10:26
  • so basically no other way that to put all the inline code for each element if they have to be manipulated. it's a shame there isn't a better option – prastor159 Jun 18 '21 at 10:39
  • Yes, and if you have multiple manage them with a Web Component (or similar code to manage multiple SVGs) [This SO answer](https://stackoverflow.com/questions/67917025/replace-specific-content-in-line-in-html-with-js/67918739#67918739) shows how to use a Web Component, **and** how to create **dynamic** SVG content – Danny '365CSI' Engelman Jun 18 '21 at 13:23
  • And [this Dev.to post](https://dev.to/dannyengelman/load-file-web-component-add-external-content-to-the-dom-1nd) shows how to keep an **external** SVG file and load/inline it multiple times. – Danny '365CSI' Engelman Jun 18 '21 at 13:28
  • Thanks I will look into that – prastor159 Jun 18 '21 at 18:36
  • See: https://stackoverflow.com/a/47744322/1601122 - "...shadow element inherits styles from the referencing `` element. This means that as long as the referenced element does not set the styles itself in the sprite or in a style sheet associated with the sprite, you can change (and animate) every inheritable style property on the icon by styling the `` element." – hendalst May 23 '23 at 05:22

0 Answers0