I want to show HTML formatted text in my dynamic list in HTML. However instead of formatted text, the HTML tags are displayed. Here is the code snippet
<!DOCTYPE html>
<html>
<body>
<ul id="myList">
<li>Tea</li>
<li>Milk</li>
<li>Water</li>
</ul>
<p>Click the button to create a LI element.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.createElement("LI");
var t = document.createTextNode(" I like <i>Coffee</i>");
x.appendChild(t);
document.getElementById("myList").appendChild(x);
}
</script>
</body>
</html>
Click on Try it button, you will observe that instead of getting formatted HTML i get I get tags for italics before coffee
What is wrong in the code?
Instead of using createTextNode
, you can use innerHTML
on the element to add text that includes HTML elements, e.g.:
var x = document.createElement("LI");
x.innerHTML = " I like <i>Coffee</i>";
Working Example:
function myFunction() {
var x = document.createElement("LI");
x.innerHTML = " I like <i>Coffee</i>";
document.getElementById("myList").appendChild(x);
}
<ul id="myList">
<li>Tea</li>
<li>Milk</li>
<li>Water</li>
</ul>
<p>Click the button to create a LI element.</p>
<button onclick="myFunction()">Try it</button>
Reference: Mozilla Docs for Element.innerHTML