Print contents of an HTML element with client-side JavaScript

Printing only a specific part of a web page will keep other page elements, that are not useful on paper (navigation, framing ect.), from taking up space on the printout.

Try it out: Print only the main content of this page without the menu and header/footer.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title>JavaScript printing</title>
<script type="text/javascript">
  var win=null;
  function printIt(printThis)
  {
    win = window.open();
    self.focus();
    win.document.open();
    win.document.write('<'+'html'+'><'+'head'+'><'+'style'+'>');
    win.document.write('body, td { font-family: Verdana; font-size: 10pt;}');
    win.document.write('<'+'/'+'style'+'><'+'/'+'head'+'><'+'body'+'>');
    win.document.write(printThis);
    win.document.write('<'+'/'+'body'+'><'+'/'+'html'+'>');
    win.document.close();
    win.print();
    win.close();
  }
</script>
</head>
<body>
<a href="#" onclick="printIt(document.getElementById('printme').innerHTML); return false">
Print
</a>
<br />
<div id="printme">Only this part of the page is printed</div>
</body>
</html>
Page last updated 2008-09-05 21:39. Some rights reserved (CC by 3.0)