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.
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>