How can I display HTML tags as Text using jQuery?
Solution 1
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.
Solution 2
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>
Solution 3
escapeHTML {
return html.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
Thats the way prototype handles it.
Solution 4
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>
Cyril
Updated on June 05, 2022Comments
-
Cyril almost 2 years
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>
-
Bojan Kovacevic almost 10 yearshe get same result as you. i think he want to see <html> and <body> elements too.
-
Cyril almost 10 yearsit still does not change the output. tags <html>, <head> and <body> are still missing in the output.
-
Bojan Kovacevic almost 10 years@webSpider yes, nice way to "cheat" browser :D
-
Ullas almost 10 years@webSpider: Now you don't need the replace function.
-
Quentin almost 10 yearsYou don't need the JavaScript at all.