-2

I needed to print the content of HTML div. For that I have added a button. I am trying to call a function onclick of button to print the div content using Javascript.

2 Answers2

0

You can add an id to the div and use: printWindow.document.write(document.getElementById("yourId").innerHtml)

Paolo Mossini
  • 1,064
  • 2
  • 15
  • 23
0

Below is the sample code to print a div on button click.

<body>
<div id='printarea'>
    <p>This is a sample text</p>
</div>
<button onclick="print()">Print</button>
</body>

<script>
function print() {
    var divToPrint = document.getElementById('printarea');
    var htmlToPrint = '' +
        '<style type="text/css">' +
        'table th, table td {' +
        'border:1px solid #000;' +
        'padding;0.5em;' +
        '}' +
        '</style>';
    htmlToPrint += divToPrint.outerHTML;
    newWin = window.open("");
    newWin.document.write("<h3 align='center'>Print Page</h3>");
    newWin.document.write(htmlToPrint);
    newWin.print();
    newWin.close();
}
</script>
Jaydeep
  • 1,686
  • 1
  • 16
  • 29