Print div contents using JavaScript

Mohammed Imtiyaz Mar 6, 2015

This tutorial will explain you how to print div contents on a web page using JavaScript.

<!DOCTYPE html>
<html>
  <head>
      <title>Print div contents using JavaScript</title>
  </head>

  <body>
      <div id="div1" style="width: 550px">
            Div Contents Here...
      </div><br/>
      <input id="Button1" type="button" value="Print" onclick="Print('div1')" />
  </body>
</html>

Javascript

<script language ="javascript" type ="text/javascript">

    function Print(el) {
        var printContent = document.getElementById(el).innerHTML;
        printWindow = window.open("", "myWindow", "top=120, left=200, width=550, height=400, dependant=no, location=0, alwaysRaised=no, menubar=no, resizeable=no, scrollbars=yes, toolbar=no, status=no, center=yes");
        printWindow.document.write("<div>");
        printWindow.document.write("" + printContent + "");
        printWindow.document.write("</div>");
        printWindow.document.close();
        printWindow.print();
        printWindow.close();
    }

</script>