-1

I am trying to display an SVG element within HTML in a tooltip and the SVG tag just gets removed before display. I have tried various methods and I cannot get this to work.

I do not understand why this is not working, could anyone give me a pointer as to what is going on?

Here is an example of something similar which is also failing:

var html = "<svg xmlns='http://www.w3.org/2000/svg' version='1.1' viewBox='0 0 16 16' width='16' height='16' aria-hidden='true'><path fill='currentColor' d='M11.536 3.464a5 5 0 010 7.072L8 14.07l-3.536-3.535a5 5 0 117.072-7.072v.001zm1.06 8.132a6.5 6.5 0 10-9.192 0l3.535 3.536a1.5 1.5 0 002.122 0l3.535-3.536zM8 9a2 2 0 100-4 2 2 0 000 4z'></path></svg>";

var element = document.getElementById("content");
element.html = html;
<div id='content'></div>
Samuel Johnson
  • 243
  • 3
  • 10
  • Does this answer your question? [How can I add a SVG graphic dynamically using javascript or jquery?](https://stackoverflow.com/questions/32637811/how-can-i-add-a-svg-graphic-dynamically-using-javascript-or-jquery) – 0stone0 Apr 07 '21 at 19:28

1 Answers1

1

Use the innerHTML property setter.

const svgContent = "<svg xmlns='http://www.w3.org/2000/svg' version='1.1' viewBox='0 0 16 16' width='16' height='16' aria-hidden='true'><path fill='currentColor' d='M11.536 3.464a5 5 0 010 7.072L8 14.07l-3.536-3.535a5 5 0 117.072-7.072v.001zm1.06 8.132a6.5 6.5 0 10-9.192 0l3.535 3.536a1.5 1.5 0 002.122 0l3.535-3.536zM8 9a2 2 0 100-4 2 2 0 000 4z'></path></svg>";

const contentEl = document.getElementById('content'); // Access the element
contentEl.innerHTML = svgContent;                     // Set the HTML value
<div id="content"></div>

Alternatively, you can append it to the container via:

const svgContent = "<svg xmlns='http://www.w3.org/2000/svg' version='1.1' viewBox='0 0 16 16' width='16' height='16' aria-hidden='true'><path fill='currentColor' d='M11.536 3.464a5 5 0 010 7.072L8 14.07l-3.536-3.535a5 5 0 117.072-7.072v.001zm1.06 8.132a6.5 6.5 0 10-9.192 0l3.535 3.536a1.5 1.5 0 002.122 0l3.535-3.536zM8 9a2 2 0 100-4 2 2 0 000 4z'></path></svg>";

const parseSvgString = svgString =>
  new DOMParser().parseFromString(svgString, 'image/svg+xml')
    .querySelector('svg');

const contentEl = document.getElementById('content'); // Access the target
contentEl.appendChild(parseSvgString(svgContent));    // Append SVG element
<div id="content"></div>
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132