javascripthtmlhighlightjs

js copy clean code from styled code element


I am using highlight.js, generated a block:

<pre class="code code-javascript"><label>JS</label><code class="language-javascript">equation_app.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-params">e</span>=&gt;</span>{
  autofocus(e);
  <span class="hljs-keyword">let</span> start = editor.selectionStart;
  <span class="hljs-keyword">let</span> end = editor.selectionEnd;
  tagging(<span class="hljs-string">'$'</span>, <span class="hljs-string">'$'</span>);
  editor.focus();
  <span class="hljs-keyword">if</span>(editor.selectionStart === editor.selectionEnd)editor.selectionStart = editor.selectionEnd = start + <span class="hljs-number">1</span>;
  refresh();
});</code><div class="copy">click to copy</div></pre>

I made a button to click to copy the text to user's clipboard.

function copy_to_clipboard(stritem){
    const el = document.createElement('textarea');
    el.value = stritem;
    document.body.appendChild(el);
    el.select();
    document.execCommand('copy');
    document.body.removeChild(el);
    window.alert('Successfully copied to your clipboard!'); 
}

However, I cannot directly call copy_to_clipboard(codeElement.innerHTML) since all html styling stuff are copied in.

I wonder if there is a way that I can extract clean code from styled Dom <code> element


Solution

  • Instead of use innerHTML use textContent like:

    function copy_to_clipboard() {
      const el = document.createElement('textarea');
      el.value = document.querySelector('code').textContent;
      document.body.appendChild(el);
      el.select();
      document.execCommand('copy');
      document.body.removeChild(el);
      window.alert('Successfully copied to your clipboard!');
    }
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.2.0/styles/default.min.css">
    <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.2.0/highlight.min.js"></script>
    <pre class="code code-javascript">
    <label>JS</label>
    <code class="language-javascript">
    equation_app.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-params">e</span>=&gt;</span>{
      autofocus(e);
      <span class="hljs-keyword">let</span> start = editor.selectionStart;
      <span class="hljs-keyword">let</span> end = editor.selectionEnd;
      tagging(<span class="hljs-string">'$'</span>, <span class="hljs-string">'$'</span>);
      editor.focus();
      <span class="hljs-keyword">if</span>(editor.selectionStart === editor.selectionEnd)editor.selectionStart = editor.selectionEnd = start + <span class="hljs-number">1</span>;
      refresh();
    });
    </code>
    <div class="copy" onclick="copy_to_clipboard()">click to copy</div>
    </pre>

    Reference: