Currently, I am in the process of creating a small webpage that will allow me to input code snippets for later copying using a JavaScript function. While the function works seamlessly with regular text, I encounter difficulties when attempting to include XML, HTML, or similar languages.
My initial approach involves replacing <
and >
with <
and >
, respectively, when dealing with these specialized languages. However, upon copying the snippet to the clipboard using my JavaScript function, the copied text includes <
and >
instead of the intended <
and >
.
I wonder if there is a method through which I can type out my code as-is and have it displayed correctly in the document so that I can also copy it with my JavaScript function?
Some users suggest using <pre>
and <code>
tags, but despite implementing them, they do not seem to resolve the issue:
<pre>
<code>
<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="https://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://www.example.com/home.html/</loc>
<lastmod>2020-04-21</lastmod>
<changefreq>monthly</changefreq>
<priority>1.0</priority>
</url>
</urlset>
</code>
</pre>
Despite this attempt, the code still displays incorrectly on my page:
https://www.example.com/home.html/
2020-04-21
monthly
1.0
This display issue not only disrupts the appearance on my page but also interferes with the functionality of my JavaScript copy function.
For a working example:
<h2>.htaccess</h2>
<div class="group">
<h3 class="head">Snippet Header</h3>
<div onclick="copyClipboard(1,1)">
<p>code</p>
</div>
</div>
function copyClipboard(oldNum,oldGroup) {
var codeNum = (oldNum - 1);
var groupNum = (oldGroup - 1);
var codeBox = document.getElementsByClassName("group")[groupNum].querySelectorAll("div");
var codeP = document.getElementsByClassName("group")[groupNum].querySelectorAll("p");
var temp_input = document.createElement("textarea");
document.body.appendChild(temp_input);
temp_input.value = codeP[codeNum].innerHTML;
temp_input.select();
document.execCommand("copy");
document.body.removeChild(temp_input);
};
(I plan to utilize 'groupNum' for animation purposes later in the code)
If anyone has suggestions on how to tackle this issue effectively, I would greatly appreciate it.