0

My goal is to append <svg> element from a ./public/images/x.svg file. The problem is, I can't find function to create element from a file.

What I've tried:

  1. The current solution: store the d attribute in the AppendSVG.js file.
let svg = document.createElementNS("http://www.w3.org/2000/svg","svg")
svg.setAttributeNS(null,"height", "16")
svg.setAttributeNS(null, "width", "16")

let path = document.createElementNS("http://www.w3.org/2000/svg","path")
path.setAttributeNS(null, "d", "M3.72 3.72a.75.75 0 011.06 0L8 6.94l3.22-3.22a.75.75 0 111.06 1.06L9.06 8l3.22 3.22a.75.75 0 11-1.06 1.06L8 9.06l-3.22 3.22a.75.75 0 01-1.06-1.06L6.94 8 3.72 4.78a.75.75 0 010-1.06z")

svg.appendChild(path)

document.getElementsByTagName("Body")[0].appendChild(svg)

x.svg

<svg height="16" width="16">
  <path d="M3.75 1.5a.25.25 0 00-.25.25v12.5c0 .138.112.25.25.25h9.5a.25.25 0 00.25-.25V6h-2.75A1.75 1.75 0 019 4.25V1.5H3.75zm6.75.062V4.25c0 .138.112.25.25.25h2.688a.252.252 0 00-.011-.013l-2.914-2.914a.272.272 0 00-.013-.011zM2 1.75C2 .784 2.784 0 3.75 0h6.586c.464 0 .909.184 1.237.513l2.914 2.914c.329.328.513.773.513 1.237v9.586A1.75 1.75 0 0113.25 16h-9.5A1.75 1.75 0 012 14.25V1.75z"></path>
</svg>
Jason Rich Darmawan
  • 1,607
  • 3
  • 14
  • 31

1 Answers1

0

fetch is the solution

let src = "./public/x.svg"

fetch(src)
.then((response) => {
    if (!response.ok) {
        throw Error(`Request for ${src} returned ${response.status} ${response.statusText}`)
    }
    return response.text();
})
.then((body) => {
    console.log(body.toLowerCase().trim())
    if (!(body.startsWith("<svg"))) {
        throw Error(`Resource ${src} returned an invaldi SVG file`)
    }
    const parser = new DOMParser()
    const doc = parser.parseFromString(body, "text/html")
    const fragment = doc.querySelector("svg")
    if (fragment == null) {
        throw Error(`Document does not contain svg element`)
    }
    document.getElementsByTagName("body")[0].appendChild(fragment)
})
Jason Rich Darmawan
  • 1,607
  • 3
  • 14
  • 31