Reputation: 83
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')
}
Upvotes: 8
Views: 50969
Reputation: 75993
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, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
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/
Upvotes: 15
Reputation: 3249
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 out the parts that you need.
Upvotes: 0
Reputation: 298136
This should work:
$('.snippet').each(function() {
$(this).text($(this).html());
});
Live demo: http://jsfiddle.net/RrUAA/1/
Upvotes: 10
Reputation: 47099
Maybe you want your code to be shown? http://jsfiddle.net/vVgvt/4/
$('.snippet').html().replace(/</g, "<").replace(/>/g, ">");
Upvotes: 2