dvrer
dvrer

Reputation: 629

try to show html tags as text with innerHTML

I have a string that contains HTML tags.
I want to render as an HTML element only the span tags aka <span></span>. every other tag that is not a span tag should be treated as regular text.

The result I'm trying to achieve is to color any text that I want even if it contains HTML tags.

I fail.

is there any other technique that I can try or a workaround?

var problem = ["<h1>","</h1>"];

var red_text = "<span style='color:red'>i am red </span>";

var green_text = "<span style='color:green'>" +
                                problem[0] + 
                                "i am green" +
                                problem[1] +
                                "</span>";

//the real result should have <h1> </h1>
var expected_text = red_text + "<span style='color:green'>|h1|i am green|/h1|</span>";

document.getElementById("demo").innerHTML = red_text + green_text;

document.getElementById("expected").innerHTML = expected_text;

HTML and JavaScript code at :
https://jsfiddle.net/ytLftxww/1/

Upvotes: 1

Views: 2522

Answers (3)

mshomali
mshomali

Reputation: 654

You can use &lt for < and & &gt for >.

Upvotes: 1

Sparragus
Sparragus

Reputation: 913

You need to use HTML entities to escape the < and > in those tags.

For example: "<span style='color:green'>&lt;h1&gt;i am green&lt;/h1&gt;</span>"

See the fiddle: https://jsfiddle.net/ytLftxww/1/

Upvotes: 2

Zuriel
Zuriel

Reputation: 1848

var problem = ["&lt;h1&gt;","&lt;h1&gt;"];

does unescaping the < > work for you?

updated fiddle

Upvotes: 1

Related Questions