1

I need to keep each character passed to .html() as is i.e. not encoded. For example, .html('>') to save the less-than character as >, not &lt;. How would I do this? Ideally, the solution would apply to all "special" characters e.g. <, &, etc.

<h1 id="my-title"></h1>

// JavaScript / jQuery code.
$('#my-title').html('>');
...
...
// Somewhere else in the code, I need to retrieve the value back by calling
// var v = $('#my-title').html();

3 Answers 3

2

Use text() instead of html()

var v = $('#my-title').text();
Sign up to request clarification or add additional context in comments.

Comments

1

Instead of .html() use .text() to save and retrieve the value.

$('#my-title').text('>');
var v = $('#my-title').text();

alert( v );   // alerts >

Note that you need to use .text() for saving the value as well. There's a reason why < and > become encoded...

2 Comments

The html() function makes it encoded. try this: $('#my-title').text('>'); var v = $('#my-title').html();
Sure, but if you have $('#my-title').html('<test>'); var v = $('#my-title').text(); it shows nothing because it thinks <test> is a tag. jsfiddle.net/HtbG5/2
0

text won't encode the value:

$('#my-title').html('>');
alert($('#my-title').text() + ' not encoded');
alert($('#my-title').html() + ' encoded');
​

JSFiddle DEMO

1 Comment

This works when the value is e.g. >, but, as pointed out by @Juhana, it'd fail when the value is e.g. <test>. Thanks for jsFiddle, though (+1).

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.