print div content - Print only the content of an HTML element and not the whole document
JavaScript Add commentsThis snippet will print the contents of any html element and not the entire page.
Get the contents of the innerhtml of the element. Here it is a div. We are going to print the contents of a div.
Define an iframe (better before this script).
This iframe is hidden on the screen by giving the style so and so.
Get a reference to the iframe’s contentwindow so that you can write the contents of the div in to the body of the iframe.
Use the close command like in the script else you can see that the browser is still loading the page even if you have completely written all the text into the content window.
So when you do close call you specify that there is no more contents to write to.
And then we make the iframe as the active window because when you print the active windows total body content will gets printed.
and then we call the print command. voila.
Without any modification this code snippet works well for me so hope it would be the same case for you guys.
The JavaScript code
var content = document.getElementById("divcontents"); var pri = document.getElementById("ifmcontentstoprint").contentWindow; pri.document.open(); pri.document.write(content.innerHTML); pri.document.close(); pri.focus(); pri.print();
The HTML Code
<iframe id="ifmcontentstoprint" style="height: 0px; width: 0px; position: absolute"></iframe>Why the need of an iframe?
as you all know when you print the whole document gets printed.
So we create a hidden new document with the help of an iframe and we assign the contents we want to print to the body of the iframe.
So the iframe will contain only the contents which we want to print.
And since the iframe is hidden everything will appear normal at the same the work is done.
June 11th, 2010 at 3:40 am
Thank you for sharing your stuff. I am a retired electronic and integrated circuit design engineer. I am trying to learn everything http://www. Your code is a good learning tool for me.
December 8th, 2011 at 1:20 am
I’ve been looking for this answer… thanks. One question. Where do we put the script? is it in the head area or in the button that prints? and can you create the print button in the div you are printing?