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.
Asked
Active
Viewed 682 times
-2
-
1Welcome to StackOverflow. Please refer [this](https://stackoverflow.com/help/how-to-ask) – Ms.Tamil Jun 21 '19 at 13:01
2 Answers
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
-
This will print all the div elements, What the OP wants is to print the content of the div, i.e the innerHtml or more like the innerText of the div. So this will not work here. – Ms.Tamil Jun 21 '19 at 13:03
-
This will work: printWindow.document.write(document.getElementsByTagName("div")[0].innerHtml) – Paolo Mossini Jun 21 '19 at 13:11
-
We're not sure whether OP needs the content of first div. Confirm with him and update your answer :) – Ms.Tamil Jun 21 '19 at 13:13
-
He can add an id to the div and use: printWindow.document.write(document.getElementById("yourId").innerHtml) – Paolo Mossini Jun 21 '19 at 13:17
-
1
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