0
<!DOCTYPE html>
<html>
  <head>
   <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title></title>
    <style>
      svg{ display: inline-block; }
    </style>
    <script src="my.js"></script>
  </head>
  <body>
    <embed src="sprites.svg" type="image/svg+xml" width="0" height="0" />
    <svg id="MAIN" xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%" viewBox="0 0 320 208" shape-rendering="crispEdges">
      <path d="M0 0h320v208h-320v-208z" fill="#000"/> <!-- Fill screen  -->
      <svg id="sprite1"><use xlink:href="sprites.svg#SP1" x="64" y="128"</use></svg>
      <svg id="sprite2"><use xlink:href="sprites.svg#SP2" x="64" y="128"</use></svg>
      <svg id="sprite3"><use xlink:href="sprites.svg#SP3" x="64" y="128"</use></svg>
    </svg>
    <script>
      start( 1 ); // Call Func in my.js
    </script>
  </body>
</html>

I have hundreds of sprites in "sprites.svg". How do I, in javascript add the sprites I want to the DOM via javascript. I want them added so that they are just like sprite1 to sprite3 in the example html page above, thanks Keith

aknosis
  • 3,602
  • 20
  • 33
  • check out https://github.com/jonathantneal/svg4everybody and see if you can move to that. It will be more stable than running your own – Dominik Sep 08 '17 at 06:04
  • for one thing, your `use` tag is incorrect (missing `>` before ``) - that's probably going to be the fix you need .. but, read some documentation on [](https://developer.mozilla.org/en-US/docs/Web/SVG/Element/use) – Jaromanda X Sep 08 '17 at 06:06
  • Possible duplicate of [SVG sprite in external file](https://stackoverflow.com/questions/22993408/svg-sprite-in-external-file) – aknosis Sep 08 '17 at 06:06
  • see this answer: https://stackoverflow.com/a/22996360/868321 – aknosis Sep 08 '17 at 06:06
  • Thanks for the closing tag catch ( Jaromanda X ). – Keith Watterson Sep 08 '17 at 08:24
  • The 2 links ( Aknosis ) don't seem to do what I want - Thanks – Keith Watterson Sep 08 '17 at 08:24
  • The main reason I want to add the sprites to the DOM via JS is that I have 100 pages and 1 JS file, so editing the 1 JS file is preferable to editing the 100 web pages. I have found how to add primitive SVG lines/text to my page, but not Symbol/Path from an external file. The Page above actually works ( even without the closing tag ). I understand that and xlink are depreciated, but it breaks if I remove them, thats a deferent issue. – Keith Watterson Sep 08 '17 at 08:31

1 Answers1

0

Worked it out, not as complex as I thought.

var svgURI  = "http://www.w3.org/2000/svg";
var mainSVG = document.getElementById( "MAIN" ); // my main SVG 
var svg     = document.createElementNS( svgURI, 'svg' );
svg.id      = "sprite4";
svg.innerHTML = "<use xlink:href='sprites.svg#SP4'></use>";
mainSVG.appendChild( svg );

Thanks to every one who tried to help