Actually, you should use Document.execCommand() (as you did) AND the (so cool) JavaScript Selection API.
Selection API allows you to programatically make a text selection from any HTML element on the page, and it works exactly like pressing CTRL+C on your keyboard. Usefull to quickly grab URLs, long texts, SSH keys, in one click.
You can try something like this :
var button = document.getElementById("yourButtonId");
var content = document.getElementById("yourContentElement");
button.addEventListener("click", function() {
// Define range and selection.
var range = document.createRange();
var selection = window.getSelection();
// Clear selection from any previous data.
selection.removeAllRanges();
range.selectNodeContents(content);
selection.addRange(range);
// Copy to clipboard.
document.execCommand('copy');
}, false);
Edit : One of the advantages of this method is that you can manipulate content in the clipboard after it’s been copied (escaping code, formatting numbers or dates, uppercase, lowercase, changing HTML tags, etc).