Print the content of a Div | JavaScript/jQuery
Printing a whole web-page is an easy task because it is a feature that is provided by web-browsers . However, in some situations, you may need to provide a functionality to your users for printing only a segment ( Div content ) of a web-page rather than the whole web page.
var mywindow = window.open();
var content = document.getElementById(elem).innerHTML;
mywindow.document.write(content);
mywindow.print();
In the above code, when you click the button "Print a Div" , a JavaScript popup window is created and extracted the contents of the HTML div elements to store it in a JavaScript variable. Then the contents of the HTML div elements are written to the popup window and finally the window is printed using the JavaScript Window print() command.

Print This Image...

Full Source | JavaScript
<!DOCTYPE html>
<html lang="en">
<head>
<title>Print a div content using JavaScript</title>
</head>
<body>
<div id="printThisDiv">
<h2>Print This Image...</h2>
<img src="javascript-print-div.png" alt="JS print Div" width="185" height="184">
</div>
<input type="button" onclick="printDiv('printThisDiv')" value="Print a Div" />
</body>
<script>
function printDiv(elem)
{
var mywindow = window.open();
var content = document.getElementById(elem).innerHTML;
var realContent = document.body.innerHTML;
mywindow.document.write(content);
mywindow.document.close(); // necessary for IE >= 10
mywindow.focus(); // necessary for IE >= 10*/
mywindow.print();
document.body.innerHTML = realContent;
mywindow.close();
return true;
}
</script>
</html>
Related Topics
- JavaScript Popup Boxes
- Opening a new window in JavaScript
- How to Create Drop-Down Lists in JavaScript
- How do I include a JavaScript file in another JavaScript file?
- How to get the current URL using JavaScript ?
- How to Detect a Mobile Device with JavaScript/jQuery
- How to validate an email address in JavaScript
- JavaScript Array Iteration
- How to Remove a Specific Item from an Array in JavaScript
- What is JavaScript closures?
- How To Remove a Property from a JavaScript Object
- How to get selected value from Dropdown list in JavaScript
- How do I get the current date in JavaScript?
- How to Open URL in New Tab | JavaScript
- How to delay/wait/Sleep in code execution | JavaScript
- How to round to at most 2 decimal places | JavaScript
- How to convert string to boolean | JavaScript
- How to check undefined in JavaScript?
- How To Copy to Clipboard | JavaScript
- How to encode a URL using JavaScript?
- How to force Input field to enter numbers only | JavaScript
- How to create multiline string in JavaScript
- How to Check for an Empty String in JavaScript?