Skylerdw Skylerdw - 2 months ago 6
HTML Question

Javascript HTML string - inject into document

This is the HTML I have:

<ul id="myUL">
</ul>


This is what I'm doing:

var myString = " &lt;li&gt;&lt;a href=&quot;www.google.comp&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;
$("#myUL").append(div.innerHTML);


This is what I recieve:

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


This is what I want to recieve:

<ul id="myUL">
<li>
<a href="www.google.com">Google</a>
</li>
<li>
Something Else
</li>
</ul>


Any advices?

Answer

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="http://www.google.comp">Google</a></li><li>Something Else</li>';
$("#myUL").append(myString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="myUL"></ul>

Or you can unescape the string:

var myString = "&lt;li&gt;&lt;a href=&quot;www.google.comp&quot;&gt;Google&lt;/a&gt;&lt;/li&gt;    &lt;li&gt;Something Else&lt;/li&gt;"
$("#myUL").append(htmlDecode(myString));

function htmlDecode(input){
  var e = document.createElement('div');
  e.innerHTML = input;
  return e.childNodes.length === 0 ? "" : e.childNodes[0].nodeValue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="myUL"></ul>

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

Comments