Vincent
Vincent

Reputation: 1730

jQuery How to apply text() to a variable

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

Answers (2)

Matt Coughlin
Matt Coughlin

Reputation: 18906

  1. Add the content to a temporary jQuery object using text() to escape it.
  2. Retrieve the escaped content from the temporary object using html().
  3. Prepend the escaped content to the container.

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">&lt;hello world&gt;</div>

In short, use text() to escape the content, and use html() to retrieve it without losing the escaped characters.

Upvotes: 1

pdoherty926
pdoherty926

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);
}); 

http://jsfiddle.net/AfW5k/

Upvotes: 2

Related Questions