How to convert HTML to text using jQuery?

I would like to make children of any element with the word "snippet" read as text instead of HTML. I know that for this I will need to change the characters <and >for the HTML page to read them as text. I tried to do this, but unfortunately I only have:

function(){
$('.snippet') 
}
+5
source share
5 answers

You can use jQuery function .text()which will remove HTML tags:

var text_only = $('.snippet').text();

Here is a demo: http://jsfiddle.net/meZjw/

Docs for .text(): http://api.jquery.com/text

UPDATE

Sime Vidas , .snippet, HTML :

$.each($('.snippet'), function (index, obj) {
    var $this = $(this);
    $this.html($this.text());
});

$.each(): http://jsfiddle.net/meZjw/1/

UPDATE

Aepheus , , , , , HTML, :

function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

: http://jsfiddle.net/meZjw/2/

UPDATE

.text() .html() , , , HTML- :

$.each($('.snippet'), function (index, obj) {
    var $this = $(this);
    $this.text($this.html());
});

: http://jsfiddle.net/meZjw/31/

+12

:

$('.snippet').each(function() {
  $(this).text($(this).html());
});

Live demo: http://jsfiddle.net/RrUAA/1/

+9

, , ? http://jsfiddle.net/vVgvt/4/

$('.snippet').html().replace(/</g, "&lt;").replace(/>/g, "&gt;");
+2

try it

$('.snippet').text($('.snippet').html());
0
source

This is what I use:

<span class="snippet">Who me? Why thank you.</span>
<div id="show_text"></div>
<script type="text/javascript" charset="utf-8">
 (function($) {

  var data = $('.snippet').text(); // or how ever you collect the data Object

  $('div#show_text').append( decodeURIComponent(jQuery.param(data)) );

 // debug report:
  if($.browser.mozilla){ //If you talk the talk, then you should toSource()
     console.log(data.toSource());
  }else{
     console.log(data);
  }  
 })(jQuery);
</script>

cut the parts you need.

0
source

All Articles