Replicate the action of highlighting a section of a website and copying it to the clipboard using JavaScript

I am currently in the process of transferring an outdated application to a new platform, but I'm facing difficulty understanding the changed JavaScript code.

My goal is to find a parent HTML element named "output" and then select all its child elements as if they were highlighted by the user.

Once that is done, I want to be able to copy this selection to the clipboard.

Despite my efforts, I haven't been able to find a satisfactory solution online for the initial task, and I'm concerned that even if I do solve it, there might still be obstacles with the second part.

If anyone has suggestions on how to achieve this, your help would be greatly appreciated.

EDIT: The HTML content is dynamically generated, hence I have provided a simplified version here instead of the actual layout.

<div id="output">
    <h1>My Name</h1>
    <img src="" />
</div>

What I aim to do is highlight the displayed HTML (excluding the outer HTML) and then copy it to the clipboard.

The copied result should resemble the following:

My Name

And not like this:

<div id="output"><h1>My Name</h1><img src="" /></div>

I have considered using JavaScript range for this task, but I'm unsure about how to select all the contents of the parent element "output".

Answer №1

By referring to Jason's response, you can easily achieve text copying functionality by adding the line

document.execCommand("copy");
after creating the selection.

If pasted into a document that supports text formatting preservation, such as Microsoft Word, the copied text will appear exactly as it did on the original webpage.

function selectContent(elementId) {
    let selectedElement = document.getElementById(elementId);

    if (document.body.createTextRange) {
        const range = document.body.createTextRange();
        range.moveToElementText(selectedElement);
        range.select();
    } else if (window.getSelection) {
        const selection = window.getSelection();
        const newRange = document.createRange();
        newRange.selectNodeContents(selectedElement);
        selection.removeAllRanges();
        selection.addRange(newRange);
    } else {
        console.warn("Text selection not supported in this browser.");
    }
}

const clickToCopy = document.querySelector('.click-me');
clickToCopy.addEventListener('click', () => { selectContent('output'); document.execCommand("copy");});
<div id="output">
   <h1>My Name</h1>
   <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAH4AAAB+CAYAAADiI6WIAAAPeUlEQVR4nO3cX2xU14HH8a8awJ3SWASCN3+arJ0/gIsLLKgkhq6d  ... truncated for brevity
  </div>
  <p class="click-me">Click me!</p>

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

Troubleshooting automatic login problem in VB 2013 settings

For my application, I am utilizing the most recent version of Awesomium's WebControl. The goal is for it to automatically log in when it reaches "accounts.google.com/ServiceLogin" by executing some Javascript. In my.settings.java file, I have the foll ...

Integrate the elements from the <template> section into the designated <slot> area

I am trying to retrieve template content, insert it into a custom element with shadow DOM, and style the span elements inside the template using the ::slotted selector. However, it seems like this functionality is not working as I expected. <!doctype h ...

When using $http in AngularJS, an error may occur when it

I ran a test on my PHP code independently and obtained the following output: {"tabId":1,"tabName":"Main","uId":"1"}{"tabId":2,"tabName":"Photography","uId":"1"} However, my AngularJS application is unable to receive the callback and is throwing an error ...

Using Vuetify to send a parameter from a select option to a method as a parameter

Just starting out with vuejs and encountering an issue passing parameters from a selected option to my JavaScript method. In my updateClientIsMaster method, the item is always undefined. However, when I added v-on:change="updateClientIsMaster in the & ...

Getting around CloudFlare's 100-second time-out restriction

Seeking a solution to AJAX-enable my reports and circumvent the 100-second time-out constraint enforced by CloudFlare for requests passing through its platform. For more information, visit Is it possible to increase CloudFlare time-out? The implementatio ...

Convert the class to a file upload using jQuery

I am currently working on a project involving a file upload script. I have multiple directories where the files need to be uploaded, and I'm attempting to use a single form for this purpose. So far, I have been able to change the form class using jQu ...

What is the process of connecting a Yarn module to a Docker container in another repository?

I'm currently facing a challenge in linking a module to a Docker container from another repository. To provide some background, I have a container hosting a React application named launch-control-admin. This project relies on a yarn module called @com ...

Injecting JavaScript object values into dynamically generated modal

I have a JavaScript object that contains various training courses. Each category includes multiple training courses, and each course is associated with a specific category. Currently, I am able to display the title and description of each category in a mo ...

Why does json_encode() work for one string and fail for another?

UPDATE: Resolved the issue. Initially, someone left a comment with a solution that was later deleted. Interestingly, simply adding semi-colons after the two json_encode lines fixed the problem. I'm still puzzled as to why string1 worked without a clo ...

Nested loops seem to override previous results with the final output

I am attempting to iterate through an array of months nested within an array of 'years' in order to calculate a count for each month using a custom angular filter. Initially, I set up the structure I will be looping through in the first while loo ...

I'm receiving an error at initBackend that says "Cannot read properties of undefined (reading 'Vue'). Does anyone know how I can fix this issue?

In my Vue 3 application using Pinia for state management, I am facing a issue where newly added messages are not appearing on the screen. Additionally, there seems to be a persistent error in the Vue Devtools console. The application structure consists of ...

The requested URL /api/users/register does not exist. Error 404

While creating a money manager application utilizing the MERN Stack, I encountered an issue with posting data to the database. Whenever I click on the register button, an error is thrown stating that it Cannot POST /api/users/register. Despite setting up a ...

Populating a span tag with data retrieved through Ajax

I encountered an issue with updating the totalDraftSalePrice HTML tag after a successful AJAX call. The data returned includes a field called SubtotalBasePrice, which I can visualize in JSON format, but for some reason, I am unable to update the HTML tag w ...

Vetur is experiencing issues with template functionality, such as not properly checking data and methods

I have incorporated the vetur extension into my Visual Studio Code for a Vue project using TypeScript. I recently discovered that vetur has the capability to perform type checks within the template tag for props, methods, and even variables. However, in ...

Is there a streamlined approach to signal a successful callback to $q.all without the need to define a $q.defer() variable?

Within my application, I have a mixture of synchronous and asynchronous methods. Here is an example of code from one of the controllers: $q.all([ asyncMethod1(), syncMethod1() ]) .then(function (results) { Even though I don't actually need t ...

An issue encountered while implementing a post method with fetch and Express

I'm just starting out, so I hope my question isn't too basic. My goal is to send a longitude and latitude from client-side JavaScript to a Node.js server using Fetch and Express.js. Below is the HTML code snippet: <!DOCTYPE html> <html ...

Are the features of emulation mode in IE11 identical to implementing the meta EmulateIE7 tag?

When using the IE11 browser, I encountered an interesting message on the console: “HTML1122: Internet Explorer is running in Enterprise Mode emulating IE8.” Upon researching this error code on this link, I found out that it is a mode configured by IT ...

Multiple instances of the identical 'Angular application' displayed simultaneously on the webpage

We've created a unique Angular 1.0 application that we aim to embed as a 'widget' within another website built with classic asp.net. During the development phase of our angular app, we take advantage of a range of gulp tools for tasks such ...

Unraveling HTML elements within a string using MongoDB: A step-by-step guide

Currently, I am in the process of creating a blog from scratch as a way to enhance my skills. The posts' content is stored as a long string in MongoDB with some random HTML tags added for testing purposes. I am curious about the conventional method fo ...

What are some methods for resolving the problem of CORS policy blocking access to retrieve data from Yahoo Finance?

Currently, I am attempting to retrieve the price of a stock within my pure React App by utilizing fetch. When I try to fetch without any options or configurations, using fetch(url), I encounter the following error: Access to fetch at 'https://quer ...