highlightjs with html code - javascript

How do I put my HTML code so that highlight.js prettify it ?
I tried
<pre>
<code>
<!-- HTML Prettify -->
<div>
<pre class="pre-code-ception"><code> haha </code></pre>
</div>
</code>
</pre>
I did put at the end of my file :
<script type="text/javascript">
hljs.initHighlightingOnLoad();
</script>
But everything is shown as plain HTML.

Oh, I think I understand the problem. You need to escape the HTML within the <code> element, otherwise it will be interpreted as HTML instead of text (you want the HTML displayed literally, not interpreted as part of the webpage structure).
Change every < to < and > to >, as well as any other special HTML characters in your code sample. (If you're generating the page on the fly, most languages have a utility function to escape the HTML for you.)

user2932428 solution without jQuery:
document.querySelectorAll("code").forEach(function(element) {
element.innerHTML = element.innerHTML.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
});

To add to #Cameron's answer on escaping your html:
If you have a large amount of code that you want to highlight and don't want to resort manually escaping everything, one option is to save it as a variable using heredoc syntax and use a variant of htmlspecialchars() (PHP) to escape it. Heredoc lets you save a multi-line string as a variable without having to use concatenation operators.
Then it's just a matter of echoing it within your <pre><code>...</code></pre> block.
The benefit of using this method is the code remains readable in your document.
Example:
<?php
$code = <<< EOT
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<img src="image.png" />
</body>
</html>
EOT;
?>
<pre>
<code class="html">
<?php echo htmlspecialchars( $code ); ?>
</code>
</pre>
One thing to note about using heredoc is that your closing EOT must be completely left-aligned.

you have to escape the content in <code class="html">
$('code').each(function() {
var that = $(this);
// cache the content of 'code'
var html = that.html().trim();
that.empty();
// escape the content
that.text(html);
});
hljs.initHighlightingOnLoad();

Related

Save full html page sourcecode in a Javascript variable

I search the best way to save a source code from a html page in a Javascript variable.
The html source code is loaded with php & mysql and looks like for example this:
<!DOCTYPE html>
<html>
<body>
<h2>HTML Images</h2>
<p>HTML images are defined with the img tag:</p>
<img src="w3schools.jpg" alt="W3" width="104" height="142">
</body>
</html>
If I try to simple save it to a variable
var html = "<?php echo $my_html; ?>";
I get different errors. For example Uncaught SyntaxError: Unexpected token '<'. I think the reason is that there are quotation marks, line breaks, special chars and so in the the content of $my_html. Of course I can save the html content before to an invisible textarea and take then the content of the textarea to the variable. But is there no other / better way?
You don't need to set the JavaScript variable independently. document.documentElement.outerHTML; is a reference to the HTML contents.
var markup = document.documentElement.outerHTML;
console.log(markup)
<!DOCTYPE html>
<html>
<body>
<h2>HTML Images</h2>
<p>HTML images are defined with the img tag:</p>
<img src="w3schools.jpg" alt="W3" width="104" height="142">
</body>
</html>
Since you are working with PHP, I would recommend using a native function prior to setting the JS variable.
Have you tried addslashes()?
<!DOCTYPE html>
<html>
<body>
<?php
$str = addslashes('What does "yolo" mean?');
echo($str);
?>
</body>
</html>

jQuery html() does ignore element naming (lower and bigger case)

The .html() function from jQuery does turn my XML Code to lowercase.
Is there any other method so I can receive exactly the output which I am expecting?
html = $('pre').html();
Goal is to receive the following output:
<ok:List Title="HelloWorld"></ok>
What I receive:
<ok:list title="HelloWorld"></ok>
Complete Code:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
$(document).ready(function(){
var html = $('pre').html();
console.log(html);
});
</script>
</head>
<body>
<pre>
<ok:List Title="HelloWorld"></ok>
</pre>
</body>
</html>
I know that XML Standard is lowercase. However in my situation I can't change that xml part. So I need a solution so I can have even the wrong.xml displayed 'wrongly'.
Check out this fiddle.
It's not standard but if you put your XML into a textarea you can retrieve it via .val();
i.e. your HTML could look like:
<textarea id="my-xml">
<Example>
<Node>Text</Node>
</Example>
</textarea>
Then in your javascript/jQuery:
var myxml = $('#my-xml').val(); //my will have case sensitive XML
Found here.

How can I display HTML tags as Text using jQuery?

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>
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.
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>
escapeHTML {
return html.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
}
Thats the way prototype handles it.
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>
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 &gt
<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/

Can an HTML script tag be included in a Javascript variable in a jsFiddle?

I was trying to answer a user's question here on SO with a jsFiddle example. The example was to dynamically initialized an iframe element via Javascript. The content to be displayed by the iframe was a valid html document assigned to a variable. Here's the variable assignment:
var aValidDoc = '<!DOCTYPE html PUBLIC
\"-//W3C//DTD XHTML 1.0
Transitional//EN\"
\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">
<html
xmlns=\"http://www.w3.org/1999/xhtml\">
<head><title></title><style
type=\"text/css\">#media
screen{html,body{margin:0;padding:0;height:100%;width:100%}p{margin:15px;}}</style>
</head><body><p>This is the content of
the dynmic document.</p><body></html>';
Here's a snippet of what I want to do:
</p><script type=\"text/javascript\">alert(\"Hi\")</script><body></html>';
In fact, even a comment with <script> breaks the interface:
// below line breaks jsFiddle
// <script type="text//javascript"></script>
Here's the fiddle: jsFiddle example
Is there a way to write the variable assignment to include the script tag so as not to break the jsFiddle interface?
Literally writing </script> anywhere in your inline javascript will break the containing html tag.
An easy work-around is to write "<\/script>" instead. Since it's inside a string literal, the backslash is dropped and you get "</script>"
http://jsfiddle.net/KavDy/2/
The </script> closes the script you can escape it like %3c/script> and use unescape to get it back
http://jsfiddle.net/mowglisanu/KavDy/3/
jsFiddle puts the script in a cdata-section:
<head>
...
<script type='text/javascript'>//<![CDATA[
var aValidDoc = '...<script>...</script>...';
// also in comments:
// <script type="text//javascript"></script>
//]]>
</script>
</head>
Yet, they server their documents with a content-type of text/html, so the cdata won't be parsed correctly as XHTML and the closing </script> tag breaks everything.
Getting the document through a XHTML proxy should work, but that's no option. Therefore, you will need to escape it, eg by inserting a backslash or '+' (literal concatenation).

How to make JavaScript affect only the code between specific tags

This is the source of my simple HTML page (save as .html file):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function convert(){
var ele1 = document.getElementById("somewhere");
var replaced;
replaced = ele1.value;
replaced = replaced.replace(/&/ig, "&");
replaced = replaced.replace(/</ig, "<");
replaced = replaced.replace(/>/ig, ">");
replaced = replaced.replace(/'/ig, "'");
replaced = replaced.replace(/"/ig, """);
ele1.value = replaced;
}
</script>
</head>
<body>
<textarea cols="70" id="somewhere" rows="15" style="background: none repeat scroll 0% 0% rgb(250, 250, 250); border: 2px solid rgb(204, 204, 204);"></textarea><br />
<input onclick="convert();" type="button" value="Encode" />
</body>
</html>
What this page does is, any code put in the textarea is HTML-encoded/escaped when the "Encode" button is clicked — essentially all instances of &, <, >, ' and " in the input code are replaced with their respective HTML entities.
How do I modify the JavaScript code in the page, so that only the input code between <pre> and </pre> tags is modified as aforementioned?
EDIT: As I see it I wasn't clear. First you need to save the HTML code I gave above into a .html file and open it in a browser. Then you will see a textarea/textbox with an "Encode" button below it.
Any code put into the text area is escaped when the "Encode" button is pressed.
I want to modify the JavaScript code in the HTML code above, so that (for instance) if I put the following code in the textbox:
It's mine.
<pre>
<input onclick="convert();" type="button" value="Encode" />
</pre>
It's also mine.
and hit the "Encode" button, only the code between <pre> tags is escaped. I hope I am clear this time.
Hope I am clear, and can get some help. Thanks.
Insead of using:
var ele1 = document.getElementById("somewhere");
You could use:
var ele1 = document.getElementsByTagName("pre");
However this might return multiple elements since there could be multiple <pre> sections in your html.
But again, if your goal is to produce a safe output, escaping is not a preferred solution. Have a look at Markdown for example:
http://daringfireball.net/projects/markdown/basics
I'm not sure into what you're trying to convert. ele1.innerHTML parses the HTML exactly how it should to be parsed. Ie. < will be converted to <, which is valid HTML.
Edited
function convert(){
var txt=document.getElementById('somewhere');
txt.innerText=txt.innerHTML;
return;
}
Quotemarks and hipsals are valid html, but if you want have them replaced:
var txt=document.getElementById('somewhere');
var txti=txt.innerHTML;
txti=txti.replace(/\"/g, """);
txti=txti.replace(/\'/g, "'");
txt.innerText=txti;

Categories

Resources