I am trying to implement a print feature in HTML. I know I can print the whole page with window.print()
, but how do I print only a specific page element? For example a particular <DIV>Some text to print</DIV>
.
-
1The same question has been asked before: http://stackoverflow.com/questions/468881/print-div-id-printarea-div-only – Daniel H Jan 03 '12 at 20:38
-
1Possible duplicate of [Print only?](https://stackoverflow.com/questions/468881/print-div-id-printarea-div-only) – DanMan Oct 27 '17 at 10:15
16 Answers
You could use a print specific CSS stylesheet and hide everything but what you want printed.
<div class="no-print">I won't print</div><div class="something-else">I will!</div>
Just the no-print
class will be hidden, but anything with a print class will show.
<style type="text/css" media="print">
.no-print { display: none; }
</style>

- 6,209
- 3
- 45
- 69
-
Hi manyxcxi, Any small example of doing this the CSS way? Thisis a nested– t0mcat Jun 28 '11 at 02:36many layers down.
-
The syntax for this is as follows: - this tells the browser that when it send the page to the print spool, it should use that CSS instead. – Jun 28 '11 at 02:36
-
Superstringcheese, thanks for explaining. But this solution entails that I have to add 'class="no-print"' to 10's of's on my page. Correct?– t0mcat Jun 28 '11 at 02:42
-
5Give the DIV an ID and refer to that in your print stylesheet. Set: body * {display:none;} and then #myDiv {display:normal;} (override the style only on that div). What you're doing is setting everything to invisible by default, then specifying the individual overrides you want. – Jun 28 '11 at 02:42
-
O ok.. got it. Will try to work on it.. in case I get stuck somewhere.. will post back – t0mcat Jun 28 '11 at 02:45
-
@Superstringcheese `display: normal` doesn't exist. I wish there was a generic option to turn on elements – th3an0maly May 23 '13 at 06:36
-
1@th3an0maly 'normal' meaning a normal option for that context: block, inline, etc. Sorry for the confusion. Probably most elements will be block. It's not elegant, but it will work. I normally take the approach of hiding what I *don't* want. – May 23 '13 at 13:19
-
@ashurexm is this still the valid way to implement print styles? also like such ``? – Jan 27 '17 at 02:21
-
@user2230470 That was an example of an inline style that's for print only. If you had an entire print only stylesheet you would want to do exactly as you've described using the `media` attribute on the stylesheet link. – ashurexm Jan 28 '17 at 18:32
-
-
This is not an accepted answer for me because the element in want to print is inside an other element. The other contents of that element i don't want to print – Chris P May 09 '20 at 10:11
If you are familiar to jQuery, you can use jQuery Print Element plugin like this:
$('SelectorToPrint').printElement();

- 6,382
- 2
- 24
- 32
-
-
6This does not work out of the box with newer jquery versions because it uses the "jQuery.browser" property that was removed. jQuery Doc says: _This property was removed in jQuery 1.9 and is available only through the jQuery.migrate plugin. Please try to use feature detection instead._ – Feri Dec 05 '17 at 20:48
-
-
@Softsofter this is exactly the reason why I don't like jQuery, you don't use your own logic to solve a problem, and once jQuery breaks or a plugin is out of date, you just don't know how to fix a certain situation. Better learn the depth of your browser if you want to be autonomous. – vdegenne Jan 24 '23 at 09:08
Created something generic to use on any HTML element
HTMLElement.prototype.printMe = printMe;
function printMe(query){
var myframe = document.createElement('IFRAME');
myframe.domain = document.domain;
myframe.style.position = "absolute";
myframe.style.top = "-10000px";
document.body.appendChild(myframe);
myframe.contentDocument.write(this.innerHTML) ;
setTimeout(function(){
myframe.focus();
myframe.contentWindow.print();
myframe.parentNode.removeChild(myframe) ;// remove frame
},3000); // wait for images to load inside iframe
window.focus();
}
Usage:
document.getElementById('xyz').printMe();
document.getElementsByClassName('xyz')[0].printMe();
Hope this help
Regards
Gaurav Khurana

- 33
- 7

- 821
- 9
- 11
Simple html and pure javascript works best. Parameter "this" refers to current id, so that function is universal for all ids. By using "ref.textContent" instead of "ref.innerHTML" you can extract only textual content for printing.
html body:
<div id="monitor" onclick="idElementPrint(this)">element to print
<img src="example.jpg" width="200">
</div>
pure javascript:
/*or:
monitor.textContent = "click me to print content";
const imga = new Image(200); //width
imga.src = "./example.jpg";
monitor.appendChild(imga);
*/
const idElementPrint = ref => {
const iframe = document.createElement("iframe");
iframe.style.display = "none";
document.body.appendChild(iframe);
const pri = iframe.contentWindow;
pri.document.open();
pri.document.write(ref.innerHTML);
pri.document.close();
pri.focus();
pri.print();
pri.onafterprint = () => { document.body.removeChild(iframe); }
}

- 166
- 3
- 6
-
2Super clean answer, you may want to remove the element after : `pri.onafterprint = () => { document.body.removeChild(ifram); }` – max-lt Nov 23 '20 at 10:28
-
This worked, thanks!, but it is ignoring the CSS. do you know why? some sugestions? – Emanuel Braz Jun 25 '21 at 13:20
-
1This only prints the **text** content of the element - no markup is preserved, which is not what most people are looking for. Swapping to `document.write(ref.innerHTML)` would work better. – coatesap Sep 16 '22 at 08:06
I found a solution that doesn't have the problems other solutions have. It copies the printed element to the body, and is fairly elegant and general:
CSS:
@media print {
body *:not(.printable, .printable *) {
// hide everything but printable elements and their children
display: none;
}
}
JS:
function printElement(e) {
let cloned = e.cloneNode(true);
document.body.appendChild(cloned);
cloned.classList.add("printable");
window.print();
document.body.removeChild(cloned);
}
The only limitation is that the element loses styles it inherited from its previous parents. But it works on arbitrary elements in the document structure

- 1,994
- 1
- 14
- 26
-
1This seems far superior to a lot of the other solutions - it's fast, efficient, and maintains styling from the global scope of the page. As you say, the only limitation is that you can't rely on cascading styling rules from whatever elements the printable area was contained within, but that's a minor thing, and most of the other solutions don't support this either. – coatesap Sep 16 '22 at 09:48
If you're using bootstrap, just add classname d-print-none to the elements you don't want to display in print

- 56
- 3
If you are using JQuery, you can use clone to do the following:
function printElement(e) {
var ifr = document.createElement('iframe');
ifr.style='height: 0px; width: 0px; position: absolute'
document.body.appendChild(ifr);
$(e).clone().appendTo(ifr.contentDocument.body);
ifr.contentWindow.print();
ifr.parentElement.removeChild(ifr);
}
and use like so:
printElement(document.getElementById('myElementToPrint'))

- 3,557
- 31
- 38
-
hmm, adding stylesheets manually, but it still prints it without any style – Starwave Nov 03 '17 at 10:29
-
If I understood you well you can use CSS3 to print your selected HTML element.
@media print {
body.print-element *:not(.print) {
display: none;
}
}
Notice, that you just need a selector. This allows you to easily print an element or the entire page using CSS classes.
Here you can check a working example: https://jsfiddle.net/gengns/d50m8ztu/

- 1,573
- 14
- 23
-
This only works for direct children of `body`: if `.print` is not a direct child of `body`, all of its parents get `display: none` and are hidden. See https://jsfiddle.net/bzf92rj3/ – just-max Sep 21 '22 at 18:05
If you need to print the HTML element with pure JS, you can open a window that contains only the element you want to print (without any HTML-markup).
For instance, you can print the image itself without wrapping it in any HTML by opening this image in a new window as a file.
Note: 'visible=none' doesn't actually make the window invisible, but it allows to open it as a separate window (not a tab).
afterprint event allows us to close the window when the printing dialog is closed. event.target points to the opened window instance.
Note: afterprint MUST be assigned before calling .print(), otherwise it would not be called.
let win = window.open('/absolute/image/path.jpg', '__blank', 'visible=none');
win.addEventListener('afterprint', event => event.target.close() );
win.print();
Printing an Html or a Selected Html is easy using Print.Js Add Print.Js Library
http://printjs.crabbly.com/
<form method="post" action="#" id="printJS-form">
...
</form>
<button type="button" onclick="printJS('printJS-form', 'html')">
Print Form
</button>

- 1,616
- 4
- 20
- 40
The simplest way to do it is:
elem = document.getElementById('elem').outerHTML
orig = document.documentElement.outerHTML
document.documentElement.outerHTML=elem
print()
document.documentElement.outerHTML = orig

- 594
- 7
- 13
Add this method
function printDiv(divName) {
let specific_element = document.getElementById(divName).innerHTML;
let original_elements = document.body.innerHTML;
document.body.innerHTML = specific_element;
window.print();
document.body.innerHTML = original_elements;
}

- 204
- 3
- 13
-
The biggest problem I see with this approach is that all the event listeners from original elements will be gone. – BoltKey Dec 08 '21 at 02:03
This implementation will create and apply an ad-hoc temporary style that hides all the elements on print media except the one that we want to print. After the printing the temporary style is removed, so your document will get back to its initial state.
Feel free to adjust the ad-hoc style (like papar size, margins, etc) to fit your needs.
/**
* @description Print the given element using browser built-in function
* @param {HTMLElement} element
*/
function printElement(element) {
if (!element) {
throw new Error(`Invalid print target element`);
}
const printWrapper = "print-wrapper";
const printElement = "print-element";
const css = `
body.${printWrapper} *:not(.${printElement}) {
visibility:hidden;
}
body.${printWrapper} .${printElement} {
width: 210mm;
height: 297mm;
left:0;
top:0;
position:fixed;
}
body.${printWrapper} .${printElement} * {
visibility:initial;
margin: 0;
}
`;
const head = document.getElementsByTagName("head")[0];
const style = document.createElement("style");
style.setAttribute("type", "text/css");
style.setAttribute("media", "print");
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
document.body.classList.add(printWrapper);
element.classList.add(printElement);
window.print();
document.body.classList.remove(printWrapper);
element.classList.remove(printElement);
head.removeChild(style);
}

- 3,553
- 2
- 32
- 29
function printDomElement(element) {
element.classList.add("printCss");
let printId = "printSvgId";
let name = ".printCss";
let rules = "-webkit-print-color-adjust:exact;height:100%;width:100%;position:fixed;top:0;left:0;margin:0;";
var style = document.createElement('style');
style.id = printId;
style.media = "print";
document.getElementsByTagName('head')[0].appendChild(style);
if (!(style.sheet || {}).insertRule)(style.styleSheet || style.sheet).addRule(name, rules);
else style.sheet.insertRule(name + "{" + rules + "}", 0);
window.print();
setTimeout(() => {
element.classList.remove("printCss");
let elem = document.getElementById(printId);
if (elem) elem.remove();
}, 500);
}

- 197
- 1
- 11
Set the style of the element you want to print to position:fixed,then make it cover the whole page.

- 361
- 1
- 3
- 10
-
Unreliable as content "behind" might "spill" from the bottom if it's taller than what you actually want to print or worse, cause a repeated content page printing – vsync Mar 30 '23 at 18:24
Here is another (perhaps a more modern?) solution:
<link rel="stylesheet" media="print" href="print.css">

- 9,564
- 146
- 81
- 122
-
4This isn't really an answer - it provides nothing other than a linked style sheet. Please give us the rest of the answer. – Rodney P. Barbati Oct 30 '18 at 17:03