async function copy(text) {
await navigator.clipboard.writeText(text)
}
Two things to know: it only works on HTTPS (and localhost), and it has to run in response to a user action like a click. Calling it on page load fails.
Show some feedback, people don't trust silent buttons:
button.addEventListener('click', async () => {
await copy(code.textContent)
button.textContent = 'Copied'
setTimeout(() => (button.textContent = 'Copy'), 1500)
})
The copy buttons on the code blocks of this site do exactly that.