Home > OS >  How to find element in SVG document?
How to find element in SVG document?

Time:09-27

I try to load SVG content by src then change a color of the specific element by id="el".

I use this approach:

fetch(src)
  .then((res) => res.blob())
  .then((blob) => {
    const reader = new FileReader();
    reader.onloadend = () => {
      const parser = new DOMParser();
      const doc = parser.parseFromString(reader.result.toString(), 'image/svg xml');
      console.log(doc.getElementById("el")); // null
    };
    reader.readAsDataURL(blob);
  });

As result I get null despite element "el" is presented in SVG file.

Svg look like:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
   xmlns:dc="http://purl.org/dc/elements/1.1/"
   xmlns:cc="http://creativecommons.org/ns#"
   xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
   width="50"
   height="60"
   viewBox="0 0 50 60"
   fill="none"
   version="1.1"
   id="svg8"
   sodipodi:docname="animal.svg"
   inkscape:version="0.92.2 (5c3e80d, 2017-08-06)">
  <metadata
     id="metadata14">
    <rdf:RDF>
      <cc:Work
         rdf:about="">
        <dc:format>image/svg xml</dc:format>
        <dc:type
           rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
        <dc:title></dc:title>
      </cc:Work>
    </rdf:RDF>
  </metadata>

... Here paths

I tried this way, so I get content of SVG as string:

src = `${baseHref}assets/images/${src}`;

var xhr = new XMLHttpRequest();
xhr.open('GET', src);
xhr.send();
xhr.onreadystatechange = (e) => {
  const el = e.srcElement as any;
  console.log(el?.response);
};

How to find element in this content and change the color?

CodePudding user response:

There is no need to transform this into a blob, then turn the blob into a data-URL, since you just want the raw SVG text.

Try this:

fetch(src)
  .then(res => res.text())
  .then(txt => {
    const parser = new DOMParser();
    const svg = parser.parseFromString(txt, 'image/svg xml');
    console.log(svg.getElementById("el"));
  });
  • Related