Show html code as text in div using jquery

This example shows you how to show the html as text in div using jquery with out rendering. By using jquery text() function we can assign the html code to div and additionally we have to replace the space with &nbsp; and new line(\n) with html <br/>

jQuery code

<script language="javascript"> $(document).ready(function () { $("#txtInput").on("keyup", function () { $("#divOutput").text($("#txtInput").val()); $("#divOutput").html($("#divOutput").html().replace(/\n/g, '<br/>').replace(/ /g, ' ')); }); }); </script>


Enter or copy paste html code in the below textbox


Source code

<html xmlns=""> <head> <title></title> <script type="text/javascript" src=""></script> <script language="javascript"> $(document).ready(function () { $("#txtInput").on("keyup", function () { $("#divOutput").text($("#txtInput").val()); $("#divOutput").html($("#divOutput").html().replace(/\n/g, '<br/>').replace(/ /g, ' ')); }); }); </script> </head> <body> Input<br /> <textarea id="txtInput" rows="20" style="width: 100%;"></textarea> <br /> <br /> <div id="divOutput" style="border: solid 1px #ccc; padding: 20px; background: #ffe;"> </div> </body> </html>