html copy element to clipboard code example
Example 1: how to copy text in the clipboard in js
<html>
<input type="text" value="Hello world"(Can be of your choice) id="myInput"(id is the name of the text, you can change it later)
<button onclick="Hello()">Copy Text</button>
<script>
function Hello() {
var copyText = document.getElementById('myInput')
copyText.select();
document.execCommand('copy')
console.log('Copied Text')
}
</script>
Example 2: copy to cllipboard the html element
const copyWithStyle = ( element ) => {
const doc = document;
const text = doc.getElementById( element );
let range;
let selection;
if( doc.body.createTextRange ) {
range = doc.body.createTextRange();
range.moveToElement( text );
range.select();
} else if ( window.getSelection ) {
selection = window.getSelection();
range = doc.createRange();
range.selectNodeContents( text );
selection.removeAllRanges();
selection.addRange( range );
}
document.execCommand( 'copy' );
window.getSelection().removeAllRanges();
document.getElementById( 'clickMe' ).value = 'Copied to clipboard!';
}