theJuls
theJuls

Reputation: 7460

Escape characters within an HTML tag

I have a specific div that cannot have tags within it. Whenever tags are found, I would like to escape them and display as regular text.

For example:

<div class='no-tags-div'>
   <h1>Hi!</h1>
   <p>Blablablabalablal</p>
</div>

Instead of displaying the Hi! as a header text followed by a paragraph of Blablablabalablal, I would like to literally display it with the tags:

<h1>Hi!</h1>
<p>Blablablabalablal</p>

I already have access to the content I just need to figure out how to escape any of these special characters.

Edit: I should probably specify, the content within the div is posted through an input. I am attempting to not allow users to post other tags through the input, so this isn't just static HTML text we are talking about here.

Upvotes: 0

Views: 660

Answers (1)

crimson_penguin
crimson_penguin

Reputation: 2778

You can use &lt; and &gt; to escape < and >. If you're doing this on the server side, you can find and replace those. On the client, you can use element.innerText, as D. Pardal suggested, which replaces the contents of element with a text node, rather than interpreting it as HTML.

Upvotes: 1

Related Questions