Estoy usando highlight.js , generé un bloque:
<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>=></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>Hice un botón para hacer clic para copiar el texto en el portapapeles del usuario.
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!'); } Sin embargo, no puedo llamar directamente a copy_to_clipboard(codeElement.innerHTML) ya que todas las cosas de estilo html se copian.
Me pregunto si hay alguna forma de extraer código limpio del elemento Dom <code> con estilo
En lugar de usar innerHTML , use textContent como:
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>=></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>Referencia: