Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Print Div Content Using JavaScript

4.33/5 (14 votes)
4 Dec 2012CPOL 302.4K  
JavaScript to print Div content.

Introduction

This is a small trick which I want to share with you all where instead of printing an entire window we can print a section from the page.  

Using the code

On the click of a button I have called JavaScript printDiv which will print the first DIV content.

Please refer to the below code:

XML
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Untitled Page</title>

    <script language="javascript" type="text/javascript">
        function printDiv(divID) {
            //Get the HTML of div
            var divElements = document.getElementById(divID).innerHTML;
            //Get the HTML of whole page
            var oldPage = document.body.innerHTML;

            //Reset the page's HTML with div's HTML only
            document.body.innerHTML = 
              "<html><head><title></title></head><body>" + 
              divElements + "</body>";

            //Print Page
            window.print();

            //Restore orignal HTML
            document.body.innerHTML = oldPage;

          
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div id="printablediv" style="width: 100%; background-color: Blue; height: 200px">
        Print me I am in 1st Div
    </div>
    <div id="donotprintdiv" style="width: 100%; background-color: Gray; height: 200px">
        I am not going to print
    </div>
    <input type="button" value="Print 1st Div" onclick="javascript:printDiv('printablediv')" />
    </form>
</body>
</html>

Points of Interest

This trick is very basic but nevertheless very effective.

History 

Please revert with your comments if you have any query.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)