Add Copy to clipboard button to each highlight code with JavaScript

Hi, maybe you already know this but what I found after a lot of struggle is worth sharing with others. How to add ‘Copy to clipboard’ button into Hugo’s built-in code highlighter - pygment - just solved in a few lines of JS without any library.

// copy to clipboard
const d = document;
const tempCopyInput = d.createElement('input');
d.body.appendChild(tempCopyInput); = 'fixed'; = '-1000px';
// copy to clipboard function
const copyToCB = () => {;

// Hugo outputs code `div` with `highlight` class name.
// copy from highlight container
let highlight = d.querySelectorAll('.highlight'),// or any div containing code stuff
    copyIcon = d.createElement('button');
copyIcon.innerHTML = 'copy to clipboard';
highlight.forEach((hl) => {
  hl.children[1].addEventListener('click',() => {
  let codeText = hl.childNodes[0].textContent;
  tempCopyInput.setAttribute('value', codeText);


I’m not a good at JavaScript so any suggestion will be appreciated.

1 Like