EDIT START*****
This is not a duplicate, my question is bit different than what you have referenced. here is my updated code and I see that I'm getting innerHTML when I do console.log but it does not copy, is that possible if you can have that in a jsFiddler?
html code:
<div id="mydivid">
$(document).on('click', '.btn', function() { $(this).toggleClass('active'); });
</div>
javascript code:
const copy = function() {
var el = document.getElementById('mydivid');
const textarea = document.createElement('textarea');
textarea.setAttribute("name", "codetextarea");
textarea.value = el.innerHTML;
alert(el.innerHTML);
document.body.appendChild(textarea);
textarea.select();
document.execCommand("copy");
textarea.remove();
}
EDIT END*****
I'm trying to copy code from a code tag using JavaScript. It works, but it copies the text in one long line of text. I want it to copy with the exact format, for an example see this web site: https://leetcode.com/articles/two-sum/#approach-1-brute-force
My question, how can I implement the same logic of copy
code as in the above website?
here is my code:
copy: function(component,event,text) {
// Create an hidden input
var hiddenInput = document.createElement("input");
// passed text into the input
hiddenInput.setAttribute("value", text);
// Append the hiddenInput input to the body
document.body.appendChild(hiddenInput);
// select the content
hiddenInput.select();
// Execute the copy command
document.execCommand("copy");
// Remove the input from the body after copy text
document.body.removeChild(hiddenInput);
}
` element alluded to in the question using its `textContent` property, not `innerHTML`. Nesting the `code` tag inside a `pre` tag may help with its layout in HTML as well.
– traktor Dec 04 '19 at 10:50