Reputation: 167
I am trying to display unrendered HTML code using class html
and the below jquery code.
Its working for every tag except for tags <html>
, <head>
and <body>
.
Is there a way these can also be displayed as text?
$(document).ready(function () {
$('.html').each(function () {
$(this).text($(this).html());
});
});
HTML code:
<pre>
<div class="html">
<html>
<head><title>Title</title></head>
<body>
<p>Unrendred html</p>
</body>
</html>
</div>
</pre>
Expected content:
<div class="html">
<html>
<head><title>Title</title></head>
<body>
<p>Unrendred html</p>
</body>
</html>
</div>
Actual content:
<title>Title</title>
<p>Unrendred html</p>
Upvotes: 2
Views: 18034
Reputation: 27
i tried to solve your problem by jquery but you have to add one unused <pre>
tag to your code and two lines of jquery code
if you ignore <pre>
and jquery script
on output then everything is as you wan't
<!doctype html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
var data = $('html').html();
data = "<!doctype html>\n<html lang=\"en\">\n"+data+"\n</html>";
var data = $('pre#html-code').text(data);
});
</script>
</head>
<body>
<pre id="html-code"></pre>
</body>
</html>
Upvotes: 1
Reputation: 12818
escapeHTML {
return html.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
Thats the way prototype handles it.
Upvotes: 2
Reputation: 6764
escape the <>
characters - on your html, and on your js as well use html
function instead of html()
<pre>
<div class="html">
<p>< html / ></p >
<head ><title >Title</title></head >
<body >
<p >Unrendred html</p >
</body >
</html>
</div>
</pre>
$(document).ready(function () {
$('.html').each(function () {
$(this).text($(this).html);
});
});
http://fiddle.jshell.net/p3BXK/16/
Upvotes: -1
Reputation: 1008
you need to replace the tag syntax as below
expected result at this fiddle example - http://jsfiddle.net/uEMh2/
<pre>
<div class="html">
<html>
<head><title>Title</title></head>
<body>
<p>Unrendred html</p>
</body>
</html>
</div>
</pre>
Upvotes: 3
Reputation: 943564
Your HTML is invalid. You can't have most of those tags where you are putting them.
When the browser tries to parse your invalid HTML, it hits your errors and attempts to recover from them.
The result of this is that they are never put inside the .html
element in the DOM, so when you try to convert the DOM back to HTML they won't appear.
The only way you could scrape them out of there would be to refetch the raw source code from the server and then parse the HTML yourself.
Just write the HTML correctly in the first place. If you want to render a <
character then put <
in the HTML (and so on). Don't try to escape the HTML with JavaScript after the browser has already parsed it.
Upvotes: 5