Mazzu
Mazzu

Reputation: 2839

Prevent html tag creation during html() using Jquery

I am having a string "<F1>" and whenever I add it as html to a particular div using jquery's html(), as

var str = "<F1>";

$("div").html(str);

It generates html for div as

"<f1></f1>"

But I dont want such tag creation.

I need to have div with html as

"&lt;F1&gt;"

It will be appreciated if somebody guide me, to achieve this. :(

Upvotes: 1

Views: 88

Answers (3)

Ketola
Ketola

Reputation: 2767

Use .text() instead of .html().

var str = "<F1>";

$("div").text(str);

Fiddle: http://jsfiddle.net/6942a/

To escape the HTML entities in str and use .html() you can do the following:

var str = "<F1>";
str = $("<div/>").text(str).html();

$("div").html(str);

Updated jsfiddle: http://jsfiddle.net/6942a/3/

Upvotes: 1

Arunkumar Vasudevan
Arunkumar Vasudevan

Reputation: 5330

Try this

var str = '<f1>'; 
var res = str.replace("<", "&lt;");
res=res.replace(">", "&gt;");
$("div").text(res);

Fiddle

Upvotes: 0

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

Use this :

HTML:

<div></div>
<input type="text">
<input type="button" value="ADD">

jQuery :

$(function(){
    $('input[type=button]').click(function(){
      var text = $('input[type=text]').val();
      text =text.replace('<','&#60');
      text =text.replace('>','&#62');
      $("div").html(text);
    });
});

Demo

For more information see html entities

Upvotes: 0

Related Questions