Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I convert HTML into text using jQuery?

I would like to make it so that the children of any element with the "snippet" class are read as text instead of HTML. I am aware that to do this, I would need to change the < and > signs so that the HTML page reads them as text. I have been trying to do this but unfortunately, I only have:

function(){
$('.snippet') 
}
like image 954
Krev Avatar asked Dec 16 '11 17:12

Krev


2 Answers

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

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

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

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

UPDATE

Sime Vidas has a good point, you can iterate through the different .snippet elements changing their HTML structure one at a time:

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

Here is a demo using $.each(): http://jsfiddle.net/meZjw/1/

UPDATE

Aepheus has a good point, I don't know if this is what is being asked but you can make a function that will escape HTML entities like in other languages:

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

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

UPDATE

You can also use .text() and .html() in the opposite order as my above example, to the effect of showing the HTML of an element as plain-text:

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

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

like image 92
Jasper Avatar answered Oct 08 '22 01:10

Jasper


This should work:

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

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

like image 26
Blender Avatar answered Oct 08 '22 00:10

Blender