6

Is there an easy way to convert an string to svg element in vanilla javascript (no libraries)? Like:

var data = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M5 3l3.057-3 11.943 12-11.943 12-3.057-3 9-9z"/></svg>';

//convert this string to a DOM element

Update

I solved that by using the DOMParser API https://developer.mozilla.org/en-US/docs/Web/API/DOMParser

var data = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M5 3l3.057-3 11.943 12-11.943 12-3.057-3 9-9z"/></svg>';

function createSVGElement(data) {
  var parser = new DOMParser();
  var doc = parser.parseFromString(data, "image/svg+xml");
  document.body.appendChild(doc.lastChild);
}

It worked really well, and I don' have to use a div.

2 Answers 2

6

You can create a placeholder element, set the innerHTML, then get the firstChild

var placeholder = document.createElement('div');
placeholder.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M5 3l3.057-3 11.943 12-11.943 12-3.057-3 9-9z"/></svg>';
var elem = placeholder.firstChild;
Sign up to request clarification or add additional context in comments.

Comments

2

You can use this:

var div = document.createElement('div')
document.body.appendChild(div)
div.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path d="M5 3l3.057-3 11.943 12-11.943 12-3.057-3 9-9z"/></svg>'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.