1

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. :(

1
  • If you need to escape the input string for some reason, please show the full code. In the case you have presented text() is the way to go, and there's no need to use html(). I have updated my answer with a solution that allows you to use .html() as well. Commented Jul 24, 2014 at 5:35

3 Answers 3

1

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/

Sign up to request clarification or add additional context in comments.

4 Comments

@jQueryAngryBird, the jsfiddle link you shared is something different and not related what OP asked. Please check.
I need to do with html() and the string is not fixed. It is a captured text from input element.
If you wish to use html(), then you need to ensure the input is valid html, and allow tags to be there. That's what html() is for.
jQuery Angry Bird - that's what the OP will get with .text(str). The HTML of the div will be &lt;F1&gt; . See jsfiddle.net/6942a/3
0

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

3 Comments

I am having editor say text area, in which I am adding text as "<F1>" and i am using its value to as html string to set in "div". can u plz help me for such scenario?
In that case see what @Ketola suggested in his answer.
Sorry, but i need to go with html() :( because it is used further for other functionality. Can there be any other way?
0

Try this

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

Fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.