How to Print Specific Div Content using Javascript

07 Jan 2023 | Javascript


In this tutorial, you will learn how to print specific div content using javascript. Print is a common feature of all websites or web applications, but many times, we need to print specific area of html page. If you don't know how to print specific div content of html page using javascript, just follow these simple steps.

You can print specific div content using javascript by following 3 simple steps.

Step 1: Add Id Attribute

First, we need to add attribute id "printable_div_id" to <div> element which you want to print.

	<div id='printable_div_id'>
		<h1>Printable Content</h1>
		<p>This is a printable paragraph.</p>
	</div>

Step 2: Create Print Button

In this step, we need to create a button to html page.

<button onClick="printdiv('printable_div_id');">PRINT</button>

Step 2: Create a Javascript Function

In this step, we need to create a javascript function to print specific div content of html page.

<script>
function printdiv(elem) {
  var header_str = '<html><head><title>' + document.title  + '</title></head><body>';
  var footer_str = '</body></html>';
  var new_str = document.getElementById(elem).innerHTML;
  var old_str = document.body.innerHTML;
  document.body.innerHTML = header_str + new_str + footer_str;
  window.print();
  document.body.innerHTML = old_str;
  return false;
}
</script>

Complete Code:

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Print</title>
</head>
<body>

  <div style="width: 15%; background-color: #1f386a; margin:50px 0;">
    <a href="https://www.buildwithphp.com/">
      <img src="https://www.buildwithphp.com/front/images/logo.webp" width="100%">
    </a>
  </div>

	<div id='printable_div_id'>
		<h1>Printable Content</h1>
		<p>This is a printable paragraph.</p>
	</div>

  <div>
    <h1>Outside Printable Content</h1>
    <p>This is not a printable paragraph.</p>
  </div>

	<button onClick="printdiv('printable_div_id');">PRINT</button>



<script>
function printdiv(elem) {
  var header_str = '<html><head><title>' + document.title  + '</title></head><body>';
  var footer_str = '</body></html>';
  var new_str = document.getElementById(elem).innerHTML;
  var old_str = document.body.innerHTML;
  document.body.innerHTML = header_str + new_str + footer_str;
  window.print();
  document.body.innerHTML = old_str;
  return false;
}
</script>

</body>
</html>

Buddy! I hope you relished the tutorial, and it was good to see you again. Keep learning. Keep visiting.

Related Blogs