Skip to content

Instantly share code, notes, and snippets.

@Shaxadhere
Created May 25, 2023 12:59
Show Gist options
  • Save Shaxadhere/32ad93fa900858d5f34bfb62ade00db5 to your computer and use it in GitHub Desktop.
Save Shaxadhere/32ad93fa900858d5f34bfb62ade00db5 to your computer and use it in GitHub Desktop.
function copyStyledText(elementId) {
// Step 1: Identify the element
const element = document.getElementById(elementId);
if (element) {
// Step 2: Get the text content
const text = element.textContent;
// Step 3: Create a temporary element
const tempElement = document.createElement('div');
// Step 4: Set the innerHTML
tempElement.innerHTML = text;
// Step 5: Append to the document body
document.body.appendChild(tempElement);
// Step 6: Copy to clipboard
const range = document.createRange();
range.selectNode(tempElement);
window.getSelection().removeAllRanges();
window.getSelection().addRange(range);
document.execCommand('copy');
// Step 7: Clean up
document.body.removeChild(tempElement);
console.log('Text copied to clipboard!');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment