A simple "copy this code" button in JavaScript 0 ▲ Terence Eden 34 minutes ago · Tech · hide · 0 comments Next to all the code samples on this blog is a little "copy" button. That makes it easier to grab any of the code I've shared. The HTML and JS is delightfully simple: <button onclick="navigator.clipboard.writeText( this.parentNode.getElementsByTagName('code')[0].textContent );" title="Copy code" >⧉</button> The navigator.clipboard.writeText needs a user interaction to work - so it is tied to a click on the button. It takes some plaintext content. But how to get that content? My code samples look like this: <pre itemscope itemtype=https://schema.org/SoftwareSourceCode translate=no> <button onclick="navigator.clipboard.writeText( this.parentNode.getElementsByTagName('code')[0].textContent );">⧉</button> <span> <img alt height=32 src=html.svg width=32> <span itemprop=programmingLanguage> HTML</span> </span> <code itemprop=text>[…]</code> </pre> There are various ways I could get that <code> element: Give it a unique ID (but that might clutter the code, or conflict with something else).… No comments yet. Log in to reply on the Fediverse. Comments will appear here.