Rory Rory - 15 days ago 5
HTML Question

Rendering SVG into HTML element

I have a svg in a var like below:-

var chatInProgressText = "<svg id='Layer_4' data-name='Layer 4' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'>\n <defs><style>.cls-1{fill:#474747;}.cls-2{fill:#fff;}</style></defs>\n <title>chat-live-icon</title>\n <path class='cls-1' d='M15.08,0C6.76,0,0,5.17,0,11.51,0,17.14,5.42,22,12.65,22.88L11.77,27a1.16,1.16,0,0,0,.43,1,1.14,1.14,0,0,0,.71.24,1.3,1.3,0,0,0,.35,0l.1,0c1.86-.76,4.91-4.15,6.2-5.65,6.35-1.5,10.6-5.91,10.6-11C30.15,5.17,23.39,0,15.08,0Z'/><path class='cls-2' d='M19.08,20.85a1.44,1.44,0,0,0-.78.47,37.25,37.25,0,0,1-4.53,4.56L14.4,23a1.48,1.48,0,0,0-.24-1.18,1.5,1.5,0,0,0-1.05-.61c-6.48-.71-11.37-4.87-11.37-9.68,0-5.4,6-9.79,13.35-9.79s13.35,4.39,13.35,9.79C28.43,15.81,24.67,19.56,19.08,20.85Z'/><circle class='cls-1' cx='8.14' cy='11.79' r='2'/><circle class='cls-1' cx='15.14' cy='11.79' r='2'/><circle class='cls-1' cx='22.14' cy='11.79' r='2'/>\n</svg>"


How to I render this into a img tag and a div using JavaScript. Any help will be appreciated. Thanks.

Answer

Create a div in your html, set an id for it, get the element created by ID, append the child content into the new div.

var chatInProgressText = "<svg id='Layer_4' data-name='Layer 4' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'>\n    <defs><style>.cls-1{fill:#474747;}.cls-2{fill:#fff;}</style></defs>\n    <title>chat-live-icon</title>\n    <path class='cls-1' d='M15.08,0C6.76,0,0,5.17,0,11.51,0,17.14,5.42,22,12.65,22.88L11.77,27a1.16,1.16,0,0,0,.43,1,1.14,1.14,0,0,0,.71.24,1.3,1.3,0,0,0,.35,0l.1,0c1.86-.76,4.91-4.15,6.2-5.65,6.35-1.5,10.6-5.91,10.6-11C30.15,5.17,23.39,0,15.08,0Z'/><path class='cls-2' d='M19.08,20.85a1.44,1.44,0,0,0-.78.47,37.25,37.25,0,0,1-4.53,4.56L14.4,23a1.48,1.48,0,0,0-.24-1.18,1.5,1.5,0,0,0-1.05-.61c-6.48-.71-11.37-4.87-11.37-9.68,0-5.4,6-9.79,13.35-9.79s13.35,4.39,13.35,9.79C28.43,15.81,24.67,19.56,19.08,20.85Z'/><circle class='cls-1' cx='8.14' cy='11.79' r='2'/><circle class='cls-1' cx='15.14' cy='11.79' r='2'/><circle class='cls-1' cx='22.14' cy='11.79' r='2'/>\n</svg>";
var d1 = document.getElementById('svg');
d1.insertAdjacentHTML('beforeend', chatInProgressText);

https://jsfiddle.net/s6un2fpc/1/

Comments