user320550
user320550

Reputation: 1175

Javascript: Adding '<' seems to break html

I have a scenario where i have strings which have the character '<' in it. An example of this is

<a href='#'>foobar</a> foo <bar

Using the native JavaScript (innerHTML) as well as jQuery (.html()), while trying to add it to the DOM, the text after and including < gets stripped off

<a href='#'>foobar</a> foo

I tried escaping the '<' however that escapes the <a> as well. Anchors are not the only html tag that may be there, so how can i handle in such a way that i can only encode the '<' that are not part of any html entity.

An example of the problem - http://jsfiddle.net/ovbg3p8m/

Please note i get the entire HTML from somewhere else and have to work with that.

Thanks.

Upvotes: 0

Views: 64

Answers (6)

Rajashekhar Rangappa
Rajashekhar Rangappa

Reputation: 526

you have to escape the <

var text = '<a href="#">foobar</a> foo &#60;bar foobar';

Find more here Escape html

Upvotes: 0

Halcyon
Halcyon

Reputation: 57703

Let's say your build your HTML like:

var text = "foo <bar";
var link_text = "foobar";
var html = '<a href="#">' + link_text + '</a>' + text;
$(".node").html(html);

If you escape just text and link_text (but not html) you're good.

The distinction between what is html and what isn't is very important.


In PHP there is the function htmlspecialchars which replaces &, ", ', < and > by their escaped forms: &amp; &quot; &apos; &lt; &gt;. This is sufficient to avoid breaking HTML.

Upvotes: 0

Buck3y3
Buck3y3

Reputation: 136

&lt;

is the escaping you desire for this symbol.
The key is to escape what needs to be escaped and not the tag as that is html you want to preserve.

Upvotes: 0

sebnukem
sebnukem

Reputation: 8333

Use &lt;, not <. .

Upvotes: 1

jd182
jd182

Reputation: 3260

You can use &lt; instead for a less than symbol.

Upvotes: 1

Shripathi Kamath
Shripathi Kamath

Reputation: 313

Try using the appropriate entry from the HTML name column here.

Upvotes: 0

Related Questions