Skip to content Skip to sidebar Skip to footer

Is It Possible To Create A Dom Node (and Then Appendchild It Into Some Dom Element) From An Existing Svg File?

I would really appreciate if somebody helps me to solve the following problem. There is a span-element inside of rendered DOM tree which contains some svg-element: <...> &l

Solution 1:

would be perfect to use an existing SVG-file as a source for generating a new svg-element

  • create a vanilla W3C standard Web Component <load-svg>
  • Load SVG src as text
  • set it as the <load-svg>innerHTML

<load-svgsrc="https://load-file.github.io/heart.svg"></load-svg><script>
customElements.define("load-svg", classextendsHTMLElement {
  asyncconnectedCallback(  src = this.getAttribute("src")  ) {
    this.innerHTML = await (awaitfetch( src )).text()
  }
})
</script><style>
  svg { height: 180px } /* fit in SO snippet window */</style>
  • If you need to load other content, call:
document.querySelector("load-svg")
        .connectedCallback("https://load-file.github.io/heart.svg")

Documentation and more advanced usage:

https://dev.to/dannyengelman/load-file-web-component-add-external-content-to-the-dom-1nd

Solution 2:

You can remove the original svg element by setting the innerHTML to an empty string.

const xmlns = "http://www.w3.org/2000/svg";
const boxWidth = 16;
const boxHeight = 16;

const newSVG = document.createElementNS(xmlns, "svg");
newSVG.setAttributeNS(null, "viewBox", `0 0 ${boxWidth}${boxHeight}`);
newSVG.setAttributeNS(null, "width", boxWidth);
newSVG.setAttributeNS(null, "height", boxHeight);
newSVG.style.display = "block";

const path = document.createElementNS(xmlns, "path");
path.setAttributeNS(null, "class", "b");
path.setAttributeNS(null, "d", "M160.294,147.293l-2.829-2.829a1,1,0,0,0-1.414,1.415L158.173,148l-2.122,2.121a1,1,0,0,0,1.414,1.415l2.829-2.829A1,1,0,0,0,160.294,147.293Z");
path.setAttributeNS(null, "transform", "translate(-150 -140)");

newSVG.appendChild(path);

document.getElementById('span01').innerHTML = '';
document.getElementById('span01').appendChild(newSVG);
<spanid="span01"><svg></svg></span>

Post a Comment for "Is It Possible To Create A Dom Node (and Then Appendchild It Into Some Dom Element) From An Existing Svg File?"