What is the best way to include HTML code in a document so that it appears as plain text, but can still be copied using JavaScript?

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 &lt; and &gt;, respectively, when dealing with these specialized languages. However, upon copying the snippet to the clipboard using my JavaScript function, the copied text includes &lt; and &gt; 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.

Answer №1

If you want to display code in a disabled state, consider using a textarea:

<textarea disabled rows=10 cols=70>
  <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>
</textarea>

To access the value of the textarea, you can use

document.querySelector('textarea').value
.

To make sure that users cannot modify the content, remember to include the disabled attribute.

Answer №2

It is important to convert special characters to HTML entities in your code.
When copying the content, make sure to use the `textContent` property of the element rather than `innerHTML`.

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("pre");
  var temp_input = document.createElement("textarea");
  document.body.appendChild(temp_input);
  // Copy the textContent
  temp_input.value = codeP[codeNum].textContent;
  temp_input.select();
  document.execCommand("copy");
  document.body.removeChild(temp_input);
};
<h2>.htaccess</h2>
<div class="group">
  <h3 class="head">Snippet Header</h3>
  <p>click following code to copy to clipboard</p>
  <div onclick="copyClipboard(1,1)">
    <pre>
&lt;urlset xmlns="https://www.sitemaps.org/schemas/sitemap/0.9"&gt; 
  &lt;url&gt;
    &lt;loc&gt;https://www.example.com/home.html/&lt;/loc&gt;
    &lt;lastmod&gt;2020-04-21&lt;/lastmod&gt;
    &lt;changefreq&gt;monthly&lt;/changefreq&gt;
    &lt;priority&gt;1.0&lt;/priority&gt;
  &lt;/url&gt;
&lt;/urlset&gt;
</pre>
    </div>
  </div>
  <textarea rows="10" cols="70" placeholder="paste here"></textarea>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Getting a specific value from a REST API array in JavaScript: Tips and tricks

After being stuck on this problem for 8 hours, I finally decided to seek help: In my JavaScript file, I am attempting to extract data from a REST API response. The response consists of an array of objects structured like this: [{"start":"2017-04-21 14:40 ...

What's the simplest approach for incorporating a database into an HTML document?

After completing my project website with html files, css, and javascript, I decided to enhance it by adding a login functionality and other features. However, I am now faced with the challenge of deciding which platform to use. I came across Django in Py ...

Updating Google+ url parameter dynamically without the need to reload the page

Is there a way for a user to share a link on social media platforms like Facebook and Google+ without having to refresh the page? The user can customize the link with an ajax call, ensuring that the page remains static. Here is my code for the Google Plu ...

Vue's bidirectional data binding presents a challenge when attempting to update the parent component from a child component

I have the following components: Parent Component: <template> <v-container> <v-row class="text-center"> <v-col cols="12" class="parent"> <p>I am the Parent component</p> ...

The navigation bar is malfunctioning across multiple sections, including html, css, and js

The navigation bar on my website is giving me a headache. It works perfectly when the page is at the top (home section), but as soon as it scrolls down to another section, it stops working. I've tried multiple solutions, but none seem to do the trick. ...

Tips for changing the visibility of content by combining various Bootstrap 4 display classes

Struggling to figure out a seamless way to toggle the display of a side navigation bar while incorporating multiple Bootstrap 4 display classes due to their heavy use of !important. For instance, consider this div using the display classes that I need to ...

Unable to save data in local storage

I'm enhancing an existing chrome extension while ensuring a consistent style. I am looking to implement a new feature, and I have written a script that saves the user's selection from the popup and sets a new popup based on that choice going forw ...

Utilize Knockout.js to generate a table based on a Json response

I'm currently working on a project that involves creating a table using JSON response and Knockout.js. Here's how I've set it up: First, in my JavaScript file: $(document).ready(function() { $.ajax({ method : "POST", url ...

Steps to activate the main menu of a navigation bar after choosing a submenu:

I am currently working on a bootstrap nav bar that has main menus and submenus. I am trying to figure out how to make one of the main menus highlighted after selecting its submenu. For example, when I choose "For Shippers", I want "HOW IT WORKS" to become ...

Error: Angular ng-file-upload successfully uploads file, but Node.js fails to receive it

Currently, I am working on loading and cropping a file using Angular. Many thanks to https://github.com/danialfarid/ng-file-upload SignUp2ControllerTest -- $scope.upload --> data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAg ...

Issue with Angular promise finally clause not executing

I am facing an issue with my RestService where the finally clause is not getting called in the controller method, even after assuming it would be triggered on either success or failure. My current setup involves using angular 1.3.13. var restService = { ...

FireFox Compatibility Issue with jQuery DataTables Styling

When implementing datatables with my current table, I encountered an issue where the layout appears differently in Chrome and IE compared to Firefox. In Chrome and IE, it loads correctly with a larger image: https://i.sstatic.net/g34TG.png However, when ...

Oops! There seems to be an issue as the system cannot locate the declaration file for the module called 'react-search-input'

I'm attempting to set up react-input-search, but I keep encountering an error: The system is unable to find a declaration file for the module 'react-search-input'. The implied type in '.../app/node_modules/react-search-input/lib/inde ...

How can you enhance your HTML elements by incorporating classes and other features?

At this moment, the code I have is: var carDiv = $("<div/>").appendTo("#content"); var eUl = $("<ul/>").appendTo(carDiv); How can I transform it into <ul data-role="listview"> content </ul> Instead of <ul> ...

Obtain the actual file path from a JSON response

I have set up a local express server to serve a JSON file, but I am facing an issue with displaying image files located in a local folder. The image paths are included in the JSON object that I want to display in my DOM. However, the response I receive inc ...

Interact with the screen by moving your mouse or sw

I am absolutely intrigued by this captivating visual effect. My goal is to implement this on an iPhone or iPad using touchmove functionality. Is there anyone out there who can assist me with this task? Here is the JavaScript code snippet: $(document).bin ...

Having trouble sending a file with a form using JQuery AJAX?

Looking for assistance with an AJAX function utilizing JQuery: var formData = $('#FonykerEditForm').serialize(); $.ajax ({ type: 'POST', url: '<?php echo $html->url('/fonykers/edit',true); ?>', ...

Which alternative function can I use instead of onchange without having to modify the slider beforehand in order for it to function properly?

Check out my website: alainbruno.nl/form.html to see the "Race" form and the "Age" slider. I've noticed that the minimum and maximum values of the Age slider only update correctly when you first use the slider before selecting a different race. Any id ...

The functionality of ui-view in Angularjs-ui-router seems to be experiencing some technical difficulties

I am currently developing an Angular app with multiple pages, including an index page and a register page. The code snippet below pertains to the index file of my application. <html data-ng-app="dreamflow" lang="en"> <head> <% include ...

ui-select: expected a certain input, but instead received a period (.)

After updating to the latest angular-ui-select version 0.12 with angular v1.2.27, my webpage is refusing to load and displaying the error message: expected expression, got . (a point) This error seems to be linked to the following section in my vendor.js ...