This snippet of code copies the HTML content inside the container element.

This method also preserves the HTML structure and formatting.

Hence, it is also useful for copying designed content (and not just plain text).

function copyToClipboard() {
	const container = document.querySelector('.container');

	const range = document.createRange();

	// Get the contents inside the container
	// (without the wrapper div of the container itself).
	range.selectNodeContents(container);

	// Deselect existing selections.
	window.getSelection().removeAllRanges();

	// Select the content to copy.
	window.getSelection().addRange(range);

	// Copy.
	document.execCommand('copy');

	// Deselect.
	window.getSelection().removeAllRanges();
}

We can then create a simple HTML button that will perform the copy when clicked:

<button type="button" onclick="copyToClipboard()">Copy</button>