Parag Bhingre
Parag Bhingre

Reputation: 850

How to escape HTML inside <span> or <div> tag

<h4>    
  <span class="title">
      <textarea rows="4" cols="50"> How are you. </textarea>
  </span>
</h4>

How to consider <textarea rows="4" cols="50"> How are you. </textarea> as a string and not HTML. I don't want HTML to render, I just want whatever comes into div or span it should render.

EXPECTED RESULT : <textarea rows="4" cols="50"> How are you. </textarea>

Upvotes: 3

Views: 9168

Answers (5)

BlackJohan
BlackJohan

Reputation: 76

Pure JavaScript:

document.getElementsByClassName("title")[0].innerHTML = "<div>HI!</div>";
//Result will be "HI!"
document.getElementsByClassName("title")[0].innerText = "<div>HI!</div>";
//Result will be "<div>HI!</div>"

JQuery:

$(".title").html("<div>HI!</div>");
//Result will be "HI!"
$(".title").text("<div>HI!</div>");
//Result will be "<div>HI!</div>"

As a final comment, those ways are get/set.

Upvotes: 2

mvkasatkin
mvkasatkin

Reputation: 21

With JQuery just use text() instead of html() to insert the code:

$('span').text('<textarea rows="4" cols="50"> How are you. </textarea>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<h4>    
<span class="title"></span>
</h4>

Upvotes: 1

davidbuzatto
davidbuzatto

Reputation: 9424

Using pure JavaScript, without any library, you can use a function to insert the code as a text node in some container.

function insertAsText( containerId, text ) {
    var container = document.getElementById( containerId );
    var textNode = document.createTextNode( text );
    container.appendChild( textNode );
}

insertAsText( "myDiv", "<p><textarea>test</textarea></p>");
<div id="myDiv"></div>

Upvotes: 2

You need to escape the html you want to show

&lt; is <
&quot; is ""
&gt; is >

There is an online tool that can do this for you here, but you can find many scripts that can do it for in runtime.

<h4>    
<span class="title">
&lt;textarea rows=&quot;4&quot; cols=&quot;50&quot;&gt; How are you. &lt;/textarea&gt;
</span>
</h4>

Upvotes: 2

Tom O.
Tom O.

Reputation: 5941

I just added an ID to the target textarea for convenience:

console.log(document.getElementById('txtArea'));
<h4>
  <span class="tip" 4 "=" cols="50" original-title="title"> Hi hello 
<span class="title"><textarea rows="4" cols="50" id="txtArea"> How are you. </textarea></span>
  </span>
</h4>

Upvotes: 0

Related Questions