-1

I want to copy the HTML code by clicking on the button using javascript.

 <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>

    <style>
        #data {
            background: #eee;
            width: 300px;
            padding: 13px;
            text-align: center;
            font-family: arial;
        }

    </style>
</head>

<body>

    <button type="button" onclick="copyToClipboard('data')">Copy </button>

    <textarea id="data" name="data">

<p>I Want to copy this html code1.</p>
<p>I Want to copy this html code2.</p>


</textarea>


    <script src="doc/jquery.min.js"></script>
    <script src="doc/clipboard.min.js"></script>

    <script>
        window.copyToClipboard = function(elementId) {

            var aux = document.getElementById(elementId);

            aux.select();
            document.execCommand("copy");
        }

    </script>

</body>

</html>

I try this code, but it shows the code only, and I want it to show the preview of the HTML code.like this

So how can I copy HTML code from the browser by clicking on the button?

1 Answers1

0

A textarea is a text only element.

It won't parse the HTML in its value.

What you might want to look into is a WYSIWYG editor that supports html export of its contents.

I have used TinyMCE (self-hosted, there is a paid option as well) in the past tho there are definitely other options. I have no affiliation with TinyMCE.

Edit: After clarifying, here is a sample of the code:

<button onclick="fun_name();">get outerHTML</button>
<div id="idDiv">
  <div id="data">
    <p>I Want to copy this html code1.</p>
    <p>I Want to copy this html code2.</p>
  </div>
</div>

<script>
function copyToClipboard(text) {
    var dummy = document.createElement("textarea");
    document.body.appendChild(dummy);
    dummy.value = text;
    dummy.select();
    document.execCommand("copy");
    document.body.removeChild(dummy);
}

function fun_name() {
  var elem = document.getElementById("idDiv").outerHTML;
  copyToClipboard(elem)
}
</script>
Abraham Labkovsky
  • 1,771
  • 6
  • 12
  • I want to copy my code given in my HTML file, and the code will be copy by clicking on the button. – Puja Mitra May 31 '21 at 15:54
  • You did not ask that in your q. You posted a textarea with HTML in it. To copy html from your page, select it using `element.outerHTML`. You can use a dummy textarea not shown to the user to copy to clipboard. See here: https://stackoverflow.com/a/46118025/10290918 – Abraham Labkovsky May 31 '21 at 17:36
  • I try this code, but it does not work.

    I Want to copy this html code1.

    I Want to copy this html code2.

    function fun_name() { var elem = document.getElementById("idDiv").outerHTML; alert(elem); elem.select(); document.execCommand("copy"); console.log('Copied Text') } How can I copy the HTML code from the inside of the div?
    – Puja Mitra Jun 01 '21 at 09:56
  • Added to answer – Abraham Labkovsky Jun 01 '21 at 16:53