I have a javascript object with icons in SVG format
const icons = {
// Icon for the "Add to cart" button
add: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/><path d="M0 0h24v24H0z" fill="none"/></svg>`,
// Icon for the "Remove from cart" button
remove: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M19 13H5v-2h14v2z"/><path d="M0 0h24v24H0z" fill="none"/></svg>`,
// Icon for the "Remove all from cart" button
removeAll: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M19 13H5v-2h14v2z"/><path d="M0 0h24v24H0z" fill="none"/></svg>`,
// Icon for the "Remove all from cart" button
};
I would like to use it in the HTML by
<span>{icons.add}</span>
<span>{icons.remove}</span>
Right now it is displayed as a string and icon is not rendered.
How can I achieve this?
CodePudding user response:
You need to select
the element you need to insert the svg
inside and use innerHTML
to inject the SVG
inside.
const icons = {
// Icon for the "Add to cart" button
add: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/><path d="M0 0h24v24H0z" fill="none"/></svg>`,
// Icon for the "Remove from cart" button
remove: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M19 13H5v-2h14v2z"/><path d="M0 0h24v24H0z" fill="none"/></svg>`,
// Icon for the "Remove all from cart" button
removeAll: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M19 13H5v-2h14v2z"/><path d="M0 0h24v24H0z" fill="none"/></svg>`,
// Icon for the "Remove all from cart" button
};
const addIcons = document.querySelectorAll('.add');
const removeIcons = document.querySelectorAll('.remove');
addIcons.forEach(span => span.innerHTML = icons.add)
removeIcons.forEach(span => span.innerHTML = icons.remove)
<span ></span>
<span ></span>
CodePudding user response:
I was using svelte. It has @html tag. I could simply use {@html icons.add}