Skylerdw Skylerdw - 29 days ago 4
HTML Question

Javascript HTML string - inject into document

This is the HTML I have:

<ul id="myUL">

This is what I'm doing:

var myString = " &lt;li&gt;&lt;a href=&quot;;&gt;Google&lt;/a&gt;&lt;/li&gt; &lt;li&gt;Something Else&lt;/li&gt;"

var div = document.createElement('div');
div.innerHTML = myString;

This is what I recieve:

<ul id="myUL" >
&lt;li&gt;&lt;a href=""&gt;Google&lt;/a&gt;&lt;/li&gt; &lt;li&gt;Something Else&lt;/li&gt;

This is what I want to recieve:

<ul id="myUL">
<a href="">Google</a>
Something Else

Any advices?


Firstly note that you can't append a div to a ul as it's invalid HTML. ul can only contain li as children.

The issue itself is because your string contains escaped HTML. You can either use a plain string:

var myString = '<li><a href="">Google</a></li><li>Something Else</li>';
<script src=""></script>
<ul id="myUL"></ul>

Or you can unescape the string:

var myString = "&lt;li&gt;&lt;a href=&quot;;&gt;Google&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;Something Else&lt;/li&gt;"

function htmlDecode(input){
  var e = document.createElement('div');
  e.innerHTML = input;
  return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
<script src=""></script>
<ul id="myUL"></ul>

See this question for more information on the htmlDecode() function.