This 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.
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.