Edit the text below then click the ‘Copy’ button.
Some text inside my div.
const someElement = document.querySelector('.my-div');
const button = document.querySelector('#the-button');
button.addEventListener('click', () => {
copyContent();
})
const copyContent = async () => {
try {
await navigator.clipboard.writeText(someElement.textContent);
console.log('Content copied to clipboard');
alert(`Success! Copied ${someElement.textContent} to the clipboard.`);
} catch (err) {
console.error('Failed to copy: ', err);
}
}
This uses the Clipboard API which is only available on pages served over secure (https) connections. The code above is based on code from a FreeCodeCamp article.