I have a JS function that dynamically fills the inner HTML of a div with id="code-output" with some sample HTML code:
function outputCode() {
var style = "<p>#main-container {</p><p class='indent-1'>width: 100%;</p><p>}</p>"
var body = "<p><div id='main-container'></p>" + "<p class='indent-1'><div id='header'></p>" + "<p class='indent-2'><h1>This is a header 1</h1></p>" + "<p class='indent-1'></div></p>" + "<p></div></p>"
code = "<p><!DOCTYPE html></p>" + "<p><html></p>" + "<p class='indent-1'><head></p>" + "<p class='indent-2'><meta charset='utf-8'></p>" + "<p class='indent-2'><meta name='viewport' content='width=device-width, initial-scale=1'></p>" + "<p class='indent-2'><title>My HTML Theme</title></p>" + "<p class='indent-2'><style></p>" + "<div class='code'>" + style + "</div>" + "<p class='indent-2'></style></p>" + "<p class='indent-1'></head></p>" + "<p class='indent-1'><body></p>" + "<div class='code'>" + body + "</div>" + "<p class='indent-1'></body></p>" + "<p></html></p>"
outputBlock = document.getElementById("code-output");
outputBlock.innerHTML = code;
}
Everything is static at the moment but I plan to have style and body be defined dynamically. Everything is working fine and the sample HTML code fills into the div as expected.
However, I would like to include a button to copy the sample HTML code to clipboard. I have a function to do this:
function copyHtml() {
var copyText = document.getElementById("code-output").innerHTML;
navigator.clipboard.writeText(copyText);
document.getElementById("copied-message").innerHTML = "Copied";
}
This copies all of the code, but the problem is that it copies with the HTML shorthand and I need it to copy with regular tags (e.g. <html></html>
, not <html> </html>).
Please let me know if there is any way to copy the text without the shorthand?
I have tried the above functions and it ends up copying as <html> instead of <html>
, for example.
3
Answers
You probably want to use
HTMLElement.innerText
, but I’m linking you to the MDN documentation forHTMLElement.textContent
because it discusses some of the nuances between the two.The problem is you’re trying to assign a String where you should be assigning an HTML node.
"innerText" is what you’re looking for.
innerHTML is expecting an instance of an element already existing in the DOM. You can test this out by cloning an element already in the DOM and setting the innerHTMl value to the copy of that element.
function copyHtml() {
var copyText = document.getElementById("code-output").innerHTML;
}