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

The final piece left in stitching together an array

Issue I have been struggling with this code for some time now and I can't seem to figure out the solution. I am receiving 3 values from inputs and trying to remove all the empty spaces "" in the array, but when I execute the code, it displays the foll ...

I am currently seeking a way to validate if a variable corresponds to the choice made in the dropdown menu. Any suggestions on how to accomplish this task?

I have put together a simple drop down menu. My goal is to grab the currently selected value from the drop down list, store it in a variable, and display it in the console. The ultimate objective is to compare that variable with another one to determine if ...

Express Promises Linked Together: Lack of Data in Last Stage

When handling put requests for my restful API, I utilize the findOneAndUpdate method of Mongoose. The password is left to the second step where the 'save' pre hook of Mongoose is used to hash the password. router.put("/:id", function(req, res, n ...

Discover a simple method for comparing JSON responses and UI elements by utilizing two arrays in a for loop within your Cypress automation tests

I am in need of assistance where I must compare JSON response data with UI elements. If matching elements are found, the task is to print them in a log file. This requires checking all JSON responses using a for loop. Can someone provide me with Cypress Ja ...

Is there a way to perform a nextAuth sign in using Postman?

I am currently working on implementing user authentication using NextAuth. The authentication works perfectly within my webapp, but now I want to test the sign-in functionality using Postman so that I can share the login endpoint. Below is the configuratio ...

The $scope object in AngularJS has not been properly defined and

I am facing an issue with retrieving the value of email in my controller. It always returns 'undefined'. Here is my form: <form role="form" novalidate> <div class="form-group"> <input type="email" ng-model="user.emai ...

Implementing dynamic AngularJS functionality within an older HTML structure using JQuery

I am facing an issue while trying to load dynamic content using AngularJS. In my system, I have legacy pages that utilize JQuery for dynamic loading. However, as I am developing new features with AngularJS, I am encountering the same problem with dynamic ...

Incorporating AngularJS and Bootstrap for seamless pagination experience

My JSON data looks like this: http://localhost:3001/images?page=1 {"images":[{"_id":"542e57a709d2d60000c93953","name":"image1","url":"http://www.syll.com","__v":0},{"_id":"542e58e19d237e5b790f4db2","name":"image154","url":"www.rufyge.com"},{"_id" ...

Ways to obtain every image placed onto an element

Using the img tag within div.image-block sets a background. Images can be added to .block3 through drag and drop. Is there a way to create a container that includes all elements from .image-block? <style> .image-block { position: relat ...

Avoid having Masonry load all divs simultaneously

I have experience using jQuery Masonry on Tumblr, but now I want to incorporate it into my portfolio website for displaying my photography. However, I'm struggling to find a solution that allows sets of images to load in as the user scrolls to the bot ...

Retrieve every video on React.js channel from YouTube

Currently, I am working on integrating react-youtube into my React App with the goal of accessing all videos from a specific YouTube channel. The challenge I am facing is that I need to display these videos as thumbnails, exactly how they are listed in the ...

Can you explain the contrast between window.performance and PerformanceObserver?

As I delve into exploring the performance APIs, I have come across window.performance and PerformanceObserver. These two functionalities seem to serve similar purposes. For instance, if I need to obtain the FCP time, I can retrieve it from performance.getE ...

Having trouble utilizing Reactjs Pagination to navigate through the data

I'm currently working on implementing pagination for a list of 50 records, but I'm encountering an issue. Even though I have the code below, it only displays 10 records and I'm unaware of how to show the next set of 10 records until all 50 a ...

Error: The global variable cannot be emptied due to an issue with the Ajax request

As someone who is relatively new to the world of Javascript/jquery and async, I have spent a significant amount of time reading through various forums. Unfortunately, I have yet to come across a solution that addresses my specific issue. The problem at ha ...

Unable to extract attributes from a different model within Sails.js

I'm working on populating a customer model with attributes from the address.js model. However, when trying to post JSON using Postman, I keep getting a 500 Validation Error and struggling to pinpoint the cause of the issue. Any assistance would be gre ...

An error has occurred in the callback function for the watcher "function () { return this._data.$$state }": "Error: [vuex] It is forbidden to modify the vuex store state outside of a mutation"

Here is a screenshot of the error I encountered in the console This is the method that I am using The issue seems to be happening in mounted I have also included MapState in the Computed section While my code is currently functional, I am puzzled by th ...

Angular refuses to showcase the object

Currently, I am working on a web application and facing an issue in parsing an object. I attempted to retrieve the IDs of all results but unfortunately, it is returning undefined in my console. Here's what I tried: var app = angular.module("DB", ...

Need to know how to invoke a function from an http callback function that resides in a separate file? Simply use the `app.get("/", callbackFun)` method

Directory Organization: testAPI contactDetail dispMobNo.js myModule.js index.js index.js const express = require("express"); const app = express(); const port = process.env.port || 3000; const getCustNo = require("./cont ...

Error TS2307: Module 'calculator' could not be located

Running a Sharepoint Framework project in Visual Studio Code: This is the project structure: https://i.stack.imgur.com/GAlsX.png The files are organized as follows: ComplexCalculator.ts export class ComplexCalculator { public sqr(v1: number): number ...

What's stopping the error exception from showing up on the client side?

Here's the scenario: I have an action method called SavePoint that contains some logic and throws a System.ArgumentException with the message "Error, no point found". Additionally, there is an ajax function named saveFeature which makes a GET request ...