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')
}
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/
This should work:
$('.snippet').each(function() {
$(this).text($(this).html());
});
Live demo: http://jsfiddle.net/RrUAA/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With