Reputation: 735
I am using jQuery, and have an HTML block as follows:
<div id="html-block">
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
</div>
Which renders as:
Heading 1
Heading 2
Heading 3
What I am trying to do is show what HTML was used to create this block.
If I use $(this).clone().insertAfter(this);
simply repeats what we see rendered, but what I actually want to see in my browser is:
<div id="html-block">
<h1>Heading 1</h1>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
</div>
What's the best way to do this?
Upvotes: 3
Views: 4563
Reputation: 18883
str = "250m<sup>2</sup>";
let entityMap = {
"<": "<",
">": ">",
};
str = str.replace(/(<)|(>)/g, m => entityMap[m]);
console.log(str);
Upvotes: 0
Reputation: 1342
var el = $("#html-block")
var html = el[0].outerHTML.replace(/</g, "<").replace(/>/g, ">");
el.after(html)
Notes:
Hope that helps!
EDIT: Oh, just saw the other answers; they're better :-)
Upvotes: 0
Reputation: 2168
Also see this duplicate: Escaping HTML strings with jQuery
var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
function escapeHtml(string) {
return string.replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
}
... then use
var outer = escapeHTML($(this).clone().outerHTML);
$(outer).insertAfter(this);
Upvotes: 1
Reputation: 3876
What you need to be able to do is escape the HTML before you output it so that the browser doesn't render the tags contained therein.
You can escape HTML easily using jQuery like this:
var escapedHtml = $('<div />').text($('#html-block').html());
Now you have a string with things like <div id="html-block">
which you can spit out to the browser:
$('#html-block').after($('<pre />').html(escapedHtml));
All in one you could do this:
var $htmlBlock = $('#html-block');
$('<pre />').text($htmlBlock.html()).insertAfter($htmlBlock);
Upvotes: 6