Is there an easy way to convert an string to svg element in vanilla javascript (no libraries)? Like:
var data = '<svg xmlns="" 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
var data = '<svg xmlns="" 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.
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/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/en-US/docs/Web/API/DOMParser
var data = '<svg xmlns="http://www.w3/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.
Share Improve this question edited Dec 13, 2016 at 20:53 and-k asked Dec 13, 2016 at 20:42 and-kand-k 6071 gold badge8 silver badges16 bronze badges2 Answers
Reset to default 6You can create a placeholder element, set the innerHTML
, then get the firstChild
var placeholder = document.createElement('div');
placeholder.innerHTML = '<svg xmlns="http://www.w3/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;
You can use this:
var div = document.createElement('div')
document.body.appendChild(div)
div.innerHTML = '<svg xmlns="http://www.w3/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>'