Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why won't an SVG pass to HTML using a JS string literal?

In the snippet below, I have several classes on the page. I’ve created an array based on the list of classes. Then, I’m trying to pass a string literal to that class.

This works fine if I pass a simple string, like ‘Hello World’, but it won’t work with an SVG.

Any ideas why? I don’t get any errors with the SVG, it’s just not displaying.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here’s an example using simple HTML

const myClasses = document.getElementsByClassName("myClass");

Array.prototype.forEach.call(myClasses, (myClass)=> {
  myClass.innerHTML = `<h3>Hello World</h3>`;
});
<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass"></div>

And here’s another example using the same structure, but with an SVG

const myClasses = document.getElementsByClassName("myClass");

Array.prototype.forEach.call(myClasses, (myClass)=> {
  myClass.innerHTML = `
    <svg class="myClass" width="16" height="11" viewBox="0 0 16 11" fill="none" xmlns="http://www.w3.org/2000/svg">
      <symbol id="btn-acc" viewBox="0 0 16 11">
        <path d="M0 2.82813L2 0.828126L8 6.82813L14 0.828126L16 2.82813L8 10.8281L0 2.82813Z" fill="currentColor" />
      </symbol>
    </svg>  
  `;
});
<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass"></div>

>Solution :

const myClasses = document.querySelectorAll(".myClass");

myClasses.forEach((myClass) => {
  myClass.innerHTML = `
    <svg width="16px" height="11px" viewBox="0 0 16 11" fill="black" xmlns="http://www.w3.org/2000/svg">
           <path d="M0 2.82813L2 0.828126L8 6.82813L14 0.828126L16 2.82813L8 10.8281L0 2.82813Z" fill="currentColor" />
    </svg>  
  `;
});
<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass"></div>
<div class="myClass"></div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading