dmraptis
dmraptis

Reputation: 929

Get the content of an SVG string

Let's say that we have the following simple SVG element:

const svg = `<svg width="100" height="100" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
  <g clip-path="url(#clip0)">
    <path d="M100 100C100 44.7715 55.2285 -1.95703e-06 0 -4.37114e-06L-4.37114e-06 100L100 100Z" fill="current"/>
  </g>
</svg>`

The svg variable is a string and I want to extract all the child nodes from the svg (the <g> element for the specific example but can be more elements).

How can I do that without using a DOM manipulation library like JQuery?

Upvotes: 0

Views: 1652

Answers (2)

Either use JavaScripts built in DOMParser

var p= new DOMParser()
var d= p.parseFromString(svg,"text/html")
var g= d.querySelector("svg g")

OR make your own html/xml parser from scratch by looping through each character, checking for <, if found look for some letters next for the tag, if found look for other >, get all content in between for attributes, rinse and repeat

Upvotes: 1

Rounin
Rounin

Reputation: 29463

Version 2

You can use str.split() to extract all the child elements from the <svg> as a string.

Working Example:

const svg = `<svg width="100" height="100" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
  <g clip-path="url(#clip0)">
    <path d="M100 100C100 44.7715 55.2285 -1.95703e-06 0 -4.37114e-06L-4.37114e-06 100L100 100Z" fill="current"/>
  </g>
</svg>`;

let g;
g = svg.split('xmlns="http://www.w3.org/2000/svg">')[1];
g = g.split('</svg>')[0];
g = g.trim();

console.log(g);


Version 1

I want to extract the content from the <svg> which is the element inside it.

If I've understood correctly:

  • you want to extract only the <g> element
  • you know that the <svg> contains a <g> element
  • you know that there is only one <g> element

you can use str.split() to extract the <g> from the <svg>.

Working Example:

const svg = `<svg width="100" height="100" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
  <g clip-path="url(#clip0)">
    <path d="M100 100C100 44.7715 55.2285 -1.95703e-06 0 -4.37114e-06L-4.37114e-06 100L100 100Z" fill="current"/>
  </g>
</svg>`;

let g;
g = svg.split('<g ')[1];
g = g.split('</g>')[0];
g = '<g ' + g + '</g>'

console.log(g);

Upvotes: 2

Related Questions