https://htmldom.dev/copy-text-to-the-clipboard
I get "trying to stay vanilla", but any reasonably-common snippet should either be installed from npm or published there.
For this specific issue there's a module named almost exactly the same and it restores the previous selection and focus as well: https://github.com/sindresorhus/copy-text-to-clipboard/blob/...
This is the point of published modules: your code isn't stuck into the version someone wrote in 10 minutes 5 years ago.