clipboard text in span code example

Example 1: copy clipboard with span

// Copy to clipboard on a click event
document.querySelector("#copy-button").addEventListener('click', function() {
	var reference_element = document.querySelector('#to-select-text');

	var range = document.createRange();  
	range.selectNodeContents(reference_element);

	window.getSelection().addRange(range);

	var success = document.execCommand('copy');
	if(success)
		console.log('Successfully copied to clipboard');
	else
		console.log('Unable to copy to clipboard');

	window.getSelection().removeRange(range);
});

Example 2: copy clipboard with span

<span id="to-select-text">1111 - 2222 - 3333 - 4444</span>
<button id="copy-button">Copy</button>