Reputation: 1730
I would like to apply the jQuery text() method in order to escape html content containing characters like < or > This same content is "prepended" to a div block, that is why I need < and > to be escaped
I can't figure out how to do so in this example: http://jsfiddle.net/n28uf/2/
<div class="container"></div>
jQuery(function(){
var content = '<hello world>';
jQuery('.container').prepend(content);
// Where should I apply the .text() method?
});
I tried this:
jQuery('.container').prepend(jQuery.text(content));
but I get this error message:
Uncaught RangeError: Maximum call stack size exceeded
http://jsfiddle.net/n28uf/2/ any idea of what change I should bring to the code to have it working properly?
thanks
Upvotes: 0
Views: 143
Reputation: 18906
text()
to escape it.html()
.Sample code:
<div class="container"></div>
<script type="text/javascript">
jQuery(function(){
var content = '<hello world>';
var escapedContent = jQuery('<div></div>').text(content).html();
jQuery('.container').prepend(escapedContent);
});
</script>
This results in the following generated HTML source code:
<div class="container"><hello world></div>
In short, use text()
to escape the content, and use html()
to retrieve it without losing the escaped characters.
Upvotes: 1
Reputation: 10349
What about prepending a wrapper div and then populating that using .text()
?
jQuery(function(){
var content = '<hello world>';
jQuery('.container').prepend('<div class="foo"></div>');
jQuery('.foo').text(content);
});
Upvotes: 2