html element copy to clipboard code example
Example 1: copy text to clipboard javascript
//As simple as this
navigator.clipboard.writeText("Hello World");
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!';
}