3

I'm trying to make a button to select the contents of a <code> element. However, it's not working and I am getting "content.select() is not a function

<body>
<div>
    <button type="button" id="copyButton" class="btn btn-primary" onclick="copyConfig()">Copy Config</button>
    <br><br>
    <pre><code id="contentCfg">{{ content }}</code></pre>
</div>
</body>
<script>
    function copyConfig() {
        const content = document.getElementById("contentCfg").textContent;
        content.select();
        content.setSelectionRange(0, 99999);
        document.execCommand("copy");
    }
</script>

No idea why this wouldn't work, {{ content }} automatically gets filled with text by my template serve.r

fiji
  • 228
  • 5
  • 21

2 Answers2

0

Ended up fixing it by changing the js to this (added the elem parts)

function copyConfig() {
        const content = document.getElementById("contentCfg").textContent;
        const elem = document.createElement("textarea");
        document.body.appendChild(elem)
        elem.value = content;
        elem.select();
        elem.setSelectionRange(0, 99999);
        document.execCommand("copy");
        document.body.removeChild(elem);
    }
fiji
  • 228
  • 5
  • 21
0

You can actually solve this using Document.createRange(), Range.selectNodeContents() and Window.getSelection() thus avoiding unnecessary DOM manipulation.

See the example on MDN or discussion in this question: Selecting text in an element (akin to highlighting with your mouse)

function copyConfig() {
  const contentNode = document.getElementById("contentCfg")

  const range = document.createRange();
  range.selectNodeContents(contentNode);
  
  const selection = window.getSelection();
  selection.removeAllRanges();
  selection.addRange(range);

  document.execCommand("copy");
}

const copyButton = document.getElementById('copyButton');
copyButton.addEventListener('click', copyConfig);
<div>
    <button type="button" id="copyButton" class="btn btn-primary">Copy Config</button>
    <br><br>
    <pre><code id="contentCfg">{{ content }}</code></pre>
</div>
pilchard
  • 12,414
  • 5
  • 11
  • 23