# Add Copy to clipboard button to each highlight code with JavaScript

**URL:** <https://discourse.gohugo.io/t/add-copy-to-clipboard-button-to-each-highlight-code-with-javascript/21057>\
**Category:** tips & tricks\
**Created:** [October 1, 2019, 4:20pm UTC](https://discourse.gohugo.io/t/add-copy-to-clipboard-button-to-each-highlight-code-with-javascript/21057 "2019-10-01T16:20:02Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![minaminfo](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.gohugo.io/minaminfo/32/9118_2.png) [@minaminfo](https://discourse.gohugo.io/u/minaminfo)\
**Post date:** [October 1, 2019, 4:20pm UTC](https://discourse.gohugo.io/t/add-copy-to-clipboard-button-to-each-highlight-code-with-javascript/21057/1 "2019-10-01T16:20:03Z")

</div>

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.

> <https://gist.github.com/minaminfo/86c8db246ac75063867043af86d21b95>

```auto
// copy to clipboard
const d = document;
const tempCopyInput = d.createElement('input');
d.body.appendChild(tempCopyInput);
tempCopyInput.style.position = 'fixed';
tempCopyInput.style.top = '-1000px';
// copy to clipboard function
const copyToCB = () => {
  tempCopyInput.select();
  d.execCommand('copy');
};

// 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.appendChild(copyIcon.cloneNode([true]));
  hl.children[1].addEventListener('click',() => {
  let codeText = hl.childNodes[0].textContent;
  tempCopyInput.setAttribute('value', codeText);
    copyToCB();
  })

})

```

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