In this article I will explain with an example, how to print HTML Table using JavaScript.
The HTML Table will be printed with a Print Preview using JavaScript.
HTML Markup
The following HTML Markup consists of an HTML DIV inside which there is an HTML Table and an HTML Button.
The Button has been assigned a JavaScript OnClick event handler which makes call to a JavaScript function named PrintTable.
<div id="dvContents" style="border: 1px dotted black; padding: 5px; width:305px">
    <table cellspacing="0" rules="all" border="1">
            <th>Customer Id</th>
            <td>John Hammond</td>
            <td>United States</td>
            <td>Mudassar Khan</td>
            <td>Suzanne Mathews</td>
            <td>Robert Schidner</td>
<input type="button" onclick="PrintTable();" value="Print"/>
Table CSS Styles
The following CSS styles are used for the HTML Table. The style tag has been assigned ID attribute so that it can be accessed using JavaScript.
<style id="table_style" type="text/css">
        font-family: Arial;
        font-size: 10pt;
        border: 1px solid #ccc;
        border-collapse: collapse;
    table th
        background-color: #F7F7F7;
        color: #333;
        font-weight: bold;
    table th, table td
        padding: 5px;
        border: 1px solid #ccc;
Printing HTML Table using JavaScript
When the Print button is clicked, first a JavaScript popup window is created.
Then the Table CSS styles are extracted from the style tag and is written to the popup window HTML.
And then the contents of the HTML DIV i.e. HTML Table to be printed are extracted and written to the popup window HTML.
Finally, the popup window is printed using the JavaScript Window Print command.
<script type="text/javascript">
    function PrintTable() {
        var printWindow ='', '', 'height=200,width=400');
        printWindow.document.write('<html><head><title>Table Contents</title>');
        //Print the Table CSS.
        var table_style = document.getElementById("table_style").innerHTML;
        printWindow.document.write('<style type = "text/css">');
        //Print the DIV contents i.e. the HTML Table.
        var divContents = document.getElementById("dvContents").innerHTML;
Print HTML Table using JavaScript
Browser Compatibility
The above code has been tested in the following browsers.

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.