Gordon Freeman Gordon Freeman - 3 years ago 268
jQuery Question

jQuery or vanilla JavaScript: Replace or escape all < and >

I have a div like this

<div id="asdf">
<div>
<p>ASDF IS AWESOME</p>
</div>
<h1>Just another Headline</h1>
<nav>
<ul>
<li class="listitem">Hey</li>
</ul>
</nav>
</div>


and need a
jQuery
or
vanilla JavaScript
function, method to convert the whole stuff into this

&lt;div id="asdf"
&lt;div&gt;
&lt;p>ASDF IS AWESOME&lt;/p&gt;
&lt;/div&gt;
&lt;h1>Just another Headline&lt;/h1&gt;
&lt;nav&gt;
&lt;ul&gt;
&lt;li class="listitem"Hey&lt;/li&gt;
&lt;/ul&gt;
&lt;/nav&gt;
&lt;/div&gt;


so I just want to escape the
<
and
>


I tried
.replace
and
.text()

Answer Source

Try that

var html = $('#asdf').html();
var escaped=$('<div/>').text(html).html();
console.log(escaped);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="asdf">
  <div>
    <p>ASDF IS AWESOME</p>
  </div>
  <h1>Just another Headline</h1>
  <nav>
    <ul>
      <li class="listitem">Hey</li>
    </ul>
  </nav>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download