How do i print a specific div in html?

Asked 12 years, 7 months ago

Viewed 958k times

Whats the best way to print the contents of a DIV?

Bill Paetzke

13.1k6 gold badges43 silver badges44 bronze badges

asked Feb 12, 2010 at 21:37

6

Slight changes over earlier version - tested on CHROME

function PrintElem(elem)
{
    var mywindow = window.open('', 'PRINT', 'height=400,width=600');

    mywindow.document.write('' + document.title  + '');
    mywindow.document.write('');
    mywindow.document.write('

' + document.title + '

'); mywindow.document.write(document.getElementById(elem).innerHTML); mywindow.document.write(''); mywindow.document.close(); // necessary for IE >= 10 mywindow.focus(); // necessary for IE >= 10*/ mywindow.print(); mywindow.close(); return true; }

dotancohen

28.6k33 gold badges133 silver badges192 bronze badges

answered Feb 12, 2010 at 22:06

Bill PaetzkeBill Paetzke

13.1k6 gold badges43 silver badges44 bronze badges

30

I think there is a better solution. Make your div to print cover the entire document, but only when it's printed:

@media print {
    .myDivToPrint {
        background-color: white;
        height: 100%;
        width: 100%;
        position: fixed;
        top: 0;
        left: 0;
        margin: 0;
        padding: 15px;
        font-size: 14px;
        line-height: 18px;
    }
}

answered Aug 23, 2011 at 20:54

BC.BC.

23.5k12 gold badges46 silver badges62 bronze badges

8

EDIT It's been over 13 years since the plugin mentioned below was written, as per the comments, it doesn't work any more due to changed api in jQuery, feel free to fork and add a pull request!

Although this has been said by @gabe, If you are using jQuery, you can use my printElement plugin.

There's a sample here, and more information about the plugin here.

The usage is rather straight forward, just grab an element with a jQuery selector and print it:

$("#myDiv").printElement();

I hope it helps!

answered Sep 26, 2010 at 14:57

ErikErik

8327 silver badges8 bronze badges

2

Using Jquery, simply use this function:


Your print button will look like this:


Edit: If you DO have form data that you need to keep, clone won't copy that, so you'll just need to grab all the form data and replace it after restore as so:



answered Feb 11, 2015 at 6:18

How do i print a specific div in html?

Gary HayesGary Hayes

1,6721 gold badge15 silver badges23 bronze badges

9

From here https://forums.asp.net/t/1261525.aspx

 

    

    div print




    //HTML Page //Other content you wouldn't like to print
    

    

The Div content which you want to print

//Other content you wouldn't like to print //Other content you wouldn't like to print

Husam Ebish

3,4672 gold badges18 silver badges33 bronze badges

answered Jul 19, 2012 at 8:09

huston007huston007

1,9621 gold badge16 silver badges13 bronze badges

1

i used Bill Paetzke answer to print a div contain images but it didn't work with google chrome

i just needed to add this line myWindow.onload=function(){ to make it work and here is the full code



    
    


    
This will be printed.
How do i print a specific div in html?
This will not be printed.
Nor will this.

also if someone just need to print a div with id he doesn't need to load jquery

here is pure javascript code to do this



    


    
This will be printed.
How do i print a specific div in html?
This will not be printed.
Nor will this.

i hope this can help someone

answered Dec 5, 2015 at 11:41

RobertRobert

2,0242 gold badges25 silver badges38 bronze badges

5

function printdiv(printdivname) {
    var headstr = "Booking Details";
    var footstr = "";
    var newstr = document.getElementById(printdivname).innerHTML;
    var oldstr = document.body.innerHTML;
    document.body.innerHTML = headstr+newstr+footstr;
    window.print();
    document.body.innerHTML = oldstr;
    return false;
}

This will print the div area you want and set the content back to as it was. printdivname is the div to be printed.

How do i print a specific div in html?

Kate Orlova

3,0125 gold badges11 silver badges31 bronze badges

answered Dec 4, 2012 at 6:23

TechieTechie

44k41 gold badges154 silver badges239 bronze badges

2

Create a separate print stylesheet that hides all other elements except the content you want to print. Flag it using 'media="print" when you load it:

This allows you to have a completely different stylesheet loaded for printouts.

If you want to force the browser's print dialog to appear for the page, you can do it like this on load using JQuery:

$(function() { window.print(); });

or triggered off of any other event you want such as a user clicking a button.

answered Feb 12, 2010 at 21:51

2

I authored a plugin to address this scenario. I was unhappy with the plugins out there, and set out to make something more extensive/configurable.

https://github.com/jasonday/printThis

answered Mar 10, 2013 at 23:39

JasonJason

7,48713 gold badges76 silver badges122 bronze badges

6

I think the solutions proposed so far have the following drawbacks:

  1. The CSS media query solutions assume there is only one div to print.
  2. The javascript solutions work only on certain browsers.
  3. Destroying the parent window content and recreating that creates a mess.

I have improved on the solutions above. Here is something that I have tested that works really well with the following benefits.

  1. Works on all the browsers including IE, Chrome, Safari and firefox.
  2. Doesn't destroy and reload the parent window.
  3. Can print any number of DIV's on a page.
  4. Uses HTML templates to avoid error prone string concatenation.

Key Points to note :

  1. Have to have a onload="window.print()" on the newly created window.
  2. Don't call targetwindow.close() or targetwindow.print() from the parent.
  3. Make sure you do targetwindow.document.close() and target.focus()
  4. I'm using jquery but you can do the same technique using plain javascript as well.
  5. You can see this in action here https://math.tools/table/multiplication. You can print each table separately, by clicking on the print button on the box header.





 Print Para 1
 Print Para 2
  

Para 1 : Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Para 2 : Lorem 2 ipsum 2 dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Husam Ebish

3,4672 gold badges18 silver badges33 bronze badges

answered Oct 20, 2015 at 15:57

dorsdors

1,10210 silver badges19 bronze badges

1

The accepted solution wasn't working. Chrome was printing a blank page because it wasn't loading the image in time. This approach works:

Edit: It appears the accepted solution was modified after my post. Why the downvote? This solution works as well.

    function printDiv(divName) {

        var printContents = document.getElementById(divName).innerHTML;
        w = window.open();

        w.document.write(printContents);
        w.document.write('' + 'window.onload = function() { window.print(); window.close(); };' + '');

        w.document.close(); // necessary for IE >= 10
        w.focus(); // necessary for IE >= 10

        return true;
    }

answered Nov 2, 2016 at 21:15

How do i print a specific div in html?

live-lovelive-love

44k22 gold badges216 silver badges187 bronze badges

If you want to have all the styles from the original document (including inline styles) you can use this approach.

  1. Copy the complete document
  2. Replace the body with the element your want to print.

Implementation:

class PrintUtil {
  static printDiv(elementId) {
    let printElement = document.getElementById(elementId);
    var printWindow = window.open('', 'PRINT');
    printWindow.document.write(document.documentElement.innerHTML);
    setTimeout(() => { // Needed for large documents
      printWindow.document.body.style.margin = '0 0';
      printWindow.document.body.innerHTML = printElement.outerHTML;
      printWindow.document.close(); // necessary for IE >= 10
      printWindow.focus(); // necessary for IE >= 10*/
      printWindow.print();
      printWindow.close();
    }, 1000)
  }   
}

answered Mar 15, 2018 at 14:26

2

I know this is an old question, but I solved this problem w jQuery.

function printContents(id) {
    var contents = $("#"+id).html();

    if ($("#printDiv").length == 0) {
      var printDiv = null;
      printDiv = document.createElement('div');
      printDiv.setAttribute('id','printDiv');
      printDiv.setAttribute('class','printable');
      $(printDiv).appendTo('body');
    }

    $("#printDiv").html(contents);

    window.print();

    $("#printDiv").remove();
}

CSS

  @media print {
    .non-printable, .fancybox-outer { display: none; }
    .printable, #printDiv { 
        display: block; 
        font-size: 26pt;
    }
  }

ROOT

11k5 gold badges30 silver badges43 bronze badges

answered Jan 6, 2013 at 22:17

JazzyJazzy

5,88910 gold badges50 silver badges72 bronze badges

1

Although @BC answer was the best to print a single page.

But To print multiple pages of A4 size at same time with ctrl+P following solution may help.

@media print{
html *{
    height:0px!important;
    width:0px !important;
    margin: 0px !important;
    padding: 0px !important;
    min-height: 0px !important;
    line-height: 0px !important;
    overflow: visible !important;
    visibility: hidden ;


}


/*assing myPagesClass to every div you want to print on single separate A4 page*/

 body .myPagesClass {
    z-index: 100 !important;
    visibility: visible !important;
    position: relative !important;
    display: block !important;
    background-color: lightgray !important;
    height: 297mm !important;
    width: 211mm !important;
    position: relative !important;

    padding: 0px;
    top: 0 !important;
    left: 0 !important;
    margin: 0 !important;
    orphans: 0!important;
    widows: 0!important;
    overflow: visible !important;
    page-break-after: always;

}
@page{
    size: A4;
    margin: 0mm ;
    orphans: 0!important;
    widows: 0!important;
}}

answered Jan 19, 2014 at 6:55

How do i print a specific div in html?

arslanarslan

5651 gold badge7 silver badges25 bronze badges

  • Open a new window
  • Open the document object of the new window and write into it a simple document containing nothing but the div you've got and necessary html header etc - you may also want to have the document pull in a stylesheet, depending on your content is
  • Put a script in the new page to call window.print()
  • Trigger the script

answered Feb 12, 2010 at 21:53

PointyPointy

394k59 gold badges575 silver badges607 bronze badges

Here is my jquery print plugin

(function ($) {

$.fn.printme = function () {
    return this.each(function () {
        var container = $(this);

        var hidden_IFrame = $('').attr({
            width: '1px',
            height: '1px',
            display: 'none'
        }).appendTo(container);

        var myIframe = hidden_IFrame.get(0);

        var script_tag = myIframe.contentWindow.document.createElement("script");
        script_tag.type = "text/javascript";
        script = myIframe.contentWindow.document.createTextNode('function Print(){ window.print(); }');
        script_tag.appendChild(script);

        myIframe.contentWindow.document.body.innerHTML = container.html();
        myIframe.contentWindow.document.body.appendChild(script_tag);

        myIframe.contentWindow.Print();
        hidden_IFrame.remove();

    });
};
})(jQuery);

answered Jul 27, 2012 at 10:56

karaxunakaraxuna

26.5k13 gold badges81 silver badges114 bronze badges

Here is an IFrame solution that works for IE and Chrome:

function printHTML(htmlString) {
    var newIframe = document.createElement('iframe');
    newIframe.width = '1px';
    newIframe.height = '1px';
    newIframe.src = 'about:blank';

    // for IE wait for the IFrame to load so we can access contentWindow.document.body
    newIframe.onload = function() {
        var script_tag = newIframe.contentWindow.document.createElement("script");
        script_tag.type = "text/javascript";
        var script = newIframe.contentWindow.document.createTextNode('function Print(){ window.focus(); window.print(); }');
        script_tag.appendChild(script);

        newIframe.contentWindow.document.body.innerHTML = htmlString;
        newIframe.contentWindow.document.body.appendChild(script_tag);

        // for chrome, a timeout for loading large amounts of content
        setTimeout(function() {
            newIframe.contentWindow.Print();
            newIframe.contentWindow.document.body.removeChild(script_tag);
            newIframe.parentElement.removeChild(newIframe);
        }, 200);
    };
    document.body.appendChild(newIframe);
}

answered May 19, 2014 at 0:04

kofifuskofifus

15.2k12 gold badges91 silver badges143 bronze badges

Note: This works with jQuery enabled sites only

It is very simple with this cool trick. It worked for me in Google Chrome browser. Firefox wont allow you to print to PDF without a plugin.

  1. First, open the inspector using (Ctrl + Shift + I) / (Cmd + Option + I).
  2. Type this code in the console:

var jqchild = document.createElement('script');
jqchild.src = "https://cdnjs.cloudflare.com/ajax/libs/jQuery.print/1.5.1/jQuery.print.min.js";
document.getElementsByTagName('body')[0].appendChild(jqchild);
$("#myDivWithStyles").print(); // Replace ID with yours
  1. It launches the print dialog. Take a physical print or save it to PDF(in chrome). Done!

The logic is simple. We are creating a new script tag and attaching it in front of closing body tag. We injected a jQuery print extension into the HTML. Change myDivWithStyles with your own Div tag ID. Now it takes cares of preparing a printable virtual window.

Try it on any site. Only caveat is sometimes trickily written CSS can cause missing of styles. But we get the content most of times.

How do i print a specific div in html?

anitag95

1871 silver badge15 bronze badges

answered Dec 7, 2017 at 10:02

How do i print a specific div in html?

Naren YellavulaNaren Yellavula

6,7882 gold badges28 silver badges22 bronze badges

Just use PrintJS

let printjs = document.createElement("script");
printjs.src = "https://printjs-4de6.kxcdn.com/print.min.js";
document.body.appendChild(printjs);

printjs.onload = function (){
    printJS('id_of_div_you_want_to_print', 'html');
}

answered Jan 29, 2021 at 10:25

Its bit late but I found this to be really really nice!!!

function printDiv(divID) {
    //Get the HTML of div
    var divElements = document.getElementById(divID).innerHTML;
    //Get the HTML of whole page
    var oldPage = document.body.innerHTML;

    //Reset the page's HTML with div's HTML only
    document.body.innerHTML = 
       "" + 
              divElements + "";

    //Print Page
    window.print();

    //Restore orignal HTML
    document.body.innerHTML = oldPage;
          
}

answered Jun 8, 2021 at 0:19

How do i print a specific div in html?

ShedrackShedrack

5794 silver badges19 bronze badges

1

In Opera, try:

    print_win.document.write('');
print_win.document.close(); // This bit is important
print_win.print();
print_win.close();

Josh

1,8043 gold badges18 silver badges31 bronze badges

answered Feb 19, 2013 at 18:02

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

How do i print a specific div in html?

Pang

9,223146 gold badges85 silver badges118 bronze badges

answered Apr 2, 2016 at 11:29

GauravGaurav

8139 silver badges11 bronze badges

I modified @BillPaetski answer to use querySelector, add optional CSS, remove the forced H1 tag and make title optionally specified or pulled from window. It also doesn't auto-print any more and exposes internals so they can be switched out in wrapper function or as you like.

The only two private vars are tmpWindow and tmpDoc although I believe title, css and elem access may vary it should be assumed all function arguments are private.

Code:

function PrintElem(elem, title, css) {
    var tmpWindow = window.open('', 'PRINT', 'height=400,width=600');
    var tmpDoc = tmpWindow.document;

    title = title || document.title;
    css = css || "";

    this.setTitle = function(newTitle) {
        title = newTitle || document.title;
    };

    this.setCSS = function(newCSS) {
        css = newCSS || "";
    };

    this.basicHtml5 = function(innerHTML) {
        return ''+(innerHTML || "")+'';
    };

    this.htmlHead = function(innerHTML) {
        return ''+(innerHTML || "")+'';
    };

    this.htmlTitle = function(title) {
        return ''+(title || "")+'';
    };

    this.styleTag = function(innerHTML) {
        return '';
    };

    this.htmlBody = function(innerHTML) {
        return ''+(innerHTML || "")+'';
    };

    this.build = function() {
        tmpDoc.write(
            this.basicHtml5(
                this.htmlHead(
                    this.htmlTitle(title) + this.styleTag(css)
                ) + this.htmlBody(
                    document.querySelector(elem).innerHTML
                )
            )
        );
        tmpDoc.close(); // necessary for IE >= 10
    };

    this.print = function() {
        tmpWindow.focus(); // necessary for IE >= 10*/
        tmpWindow.print();
        tmpWindow.close();
    };

    this.build();
    return this;
}

Usage:

DOMPrinter = PrintElem('#app-container');
DOMPrinter.print();

answered Feb 15, 2017 at 10:17

How do i print a specific div in html?

MrMeseesMrMesees

1,39818 silver badges22 bronze badges

4

This should work:

function printDiv(divName) {
     var printContents = document.getElementById(divName).innerHTML;
     var originalContents = document.body.innerHTML;
     document.body.innerHTML = printContents;
     window.print();
     document.body.innerHTML = originalContents;
}

answered Apr 14, 2021 at 13:39

HTML > HEAD

  

HTML > BODY

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

 
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).

answered Jul 26, 2021 at 19:54

How do i print a specific div in html?

The below code copies all relevant nodes that are targeted by the query selector, copies over their styles as seen on screen, since many parent elements used for targeting the css selectors will be missing. This causes a bit of lag if there are a lot of child nodes with a lot of styles.

Ideally you'd have a print style sheet ready, but this is for use cases where there's no print style sheet to be inserted and you wish to print as seen on screen.

If you copy the below items in the browser console on this page it will print all the code snippets on this page.

+function() {
    /**
     * copied from  https://stackoverflow.com/questions/19784064/set-javascript-computed-style-from-one-element-to-another
     * @author Adi Darachi https://stackoverflow.com/users/2318881/adi-darachi
     */
    var copyComputedStyle = function(from,to){
        var computed_style_object = false;
        //trying to figure out which style object we need to use depense on the browser support
        //so we try until we have one
        computed_style_object = from.currentStyle || document.defaultView.getComputedStyle(from,null);

        //if the browser dose not support both methods we will return null
        if(!computed_style_object) return null;

            var stylePropertyValid = function(name,value){
                        //checking that the value is not a undefined
                return typeof value !== 'undefined' &&
                        //checking that the value is not a object
                        typeof value !== 'object' &&
                        //checking that the value is not a function
                        typeof value !== 'function' &&
                        //checking that we dosent have empty string
                        value.length > 0 &&
                        //checking that the property is not int index ( happens on some browser
                        value != parseInt(value)

            };

        //we iterating the computed style object and compy the style props and the values
        for(property in computed_style_object)
        {
            //checking if the property and value we get are valid sinse browser have different implementations
                if(stylePropertyValid(property,computed_style_object[property]))
                {
                    //applying the style property to the target element
                        to.style[property] = computed_style_object[property];

                }   
        }   

    };


    // Copy over all relevant styles to preserve styling, work the way down the children tree.
    var buildChild = function(masterList, childList) {
        for(c=0; c 0) {
               buildChild(master.children, child.children);
           }
        }
    }

    /** select elements to print with query selector **/
    var printSelection = function(querySelector) {
        // Create an iframe to make sure everything is clean and ordered.
        var iframe = document.createElement('iframe');
        // Give it enough dimension so you can visually check when modifying.
        iframe.width = document.width;
        iframe.height = document.height;
        // Add it to the current document to be sure it has the internal objects set up.
        document.body.append(iframe);

        var nodes = document.querySelectorAll(querySelector);
        if(!nodes || nodes.length == 0) {
           console.error('Printing Faillure: Nothing to print. Please check your querySelector');
           return;
        }

        for(i=0; i < nodes.length; i++) {

            // Get the node you wish to print.
            var origNode = nodes[i];

            // Clone it and all it's children
            var node = origNode.cloneNode(true);

            // Copy the base style.
            copyComputedStyle(origNode, node);

            if(origNode.children && origNode.children.length > 0) {
                buildChild(origNode.children, node.children);
            }

            // Add the styled clone to the iframe. using contentWindow.document since it seems the be the most widely supported version.

            iframe.contentWindow.document.body.append(node);
        }
        // Print the window
        iframe.contentWindow.print();

        // Give the browser a second to gather the data then remove the iframe.
        window.setTimeout(function() {iframe.parentNode.removeChild(iframe)}, 1000);
    }
window.printSelection = printSelection;
}();
printSelection('.default.prettyprint.prettyprinted')

answered Aug 1, 2018 at 12:13

How do i print a specific div in html?

TschallackaTschallacka

26.9k13 gold badges89 silver badges130 bronze badges

This is realy old post but here is one my update what I made using correct answer. My solution also use jQuery.

Point of this is to use proper print view, include all stylesheets for the proper formatting and also to be supported in the most browsers.

function PrintElem(elem, title, offset)
{
    // Title constructor
    title = title || $('title').text();
    // Offset for the print
    offset = offset || 0;

    // Loading start
    var dStart = Math.round(new Date().getTime()/1000),
        $html = $('html');
        i = 0;

    // Start building HTML
    var HTML = ' meta').each(function(){
        var $this = $(this),
            $meta = '';

        // Let's pickup all CSS files for the formatting
        $('head > link[rel="stylesheet"]').each(function(){
            HTML+= '';
            i++;
        }).promise().done(function(){
            // Print setup
            HTML+= '';

            // Finish HTML
            HTML+= '';
            HTML+= '

' + title + '

'; HTML+= elem.html(); HTML+= ''; // Open new window var printWindow = window.open('', 'PRINT', 'height=' + $(window).height() + ',width=' + $(window).width()); // Append new window HTML printWindow.document.write(HTML); printWindow.document.close(); // necessary for IE >= 10 printWindow.focus(); // necessary for IE >= 10*/ console.log(printWindow.document); /* Make sure that page is loaded correctly */ $(printWindow).on('load', function(){ setTimeout(function(){ // Open print printWindow.print(); // Close on print setTimeout(function(){ printWindow.close(); return true; }, 3); }, (Math.round(new Date().getTime()/1000) - dStart)+i+offset); }); }); }); }

Later you simple need something like this:

$(document).on('click', '.some-print', function() {
    PrintElem($(this), 'My Print Title');
    return false;
});

Try it.

answered Jan 21, 2019 at 13:29

pass the Element to this function to print:

function printElm(elm) {
  var orig = document.body.innerHTML;

  document.body.innerHTML = elm.outerHTML;
  print();
  document.body.innerHTML = orig;
}

Lee Taylor

7,61116 gold badges33 silver badges48 bronze badges

answered Jun 25 at 12:12

How do i print a specific div in html?

MahdiMahdi

496 bronze badges

function printDomElement(element) {
    element.classList.add("printCss");

    let printId = "printId";
    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);

  }

answered Aug 17 at 4:11

How do i print a specific div in html?

Same as best answer, just in case you need to print image as i did:

In case you want to print image:

function printElem(elem)
    {
        Popup(jQuery(elem).attr('src'));
    }

    function Popup(data) 
    {
        var mywindow = window.open('', 'my div', 'height=400,width=600');
        mywindow.document.write('my div');
        mywindow.document.write('');
        mywindow.document.write('');
        mywindow.document.write('');

        mywindow.print();
        mywindow.close();

        return true;
    }

answered Oct 17, 2013 at 19:38

1

How do I print a specific element in HTML?

You could use a print specific CSS stylesheet and hide everything but what you want printed. Just the no-print class will be hidden, but anything with a print class will show. Show activity on this post. Show activity on this post.

How do I print a div in Chrome?

Make sure you keep the . html extension. Then, go to the location you saved it in, right click and choose "Open With" and then select Google Chrome from the popup that shows up. Then, once the file has opened in Chrome, press CTRL (or Command) + P, and print the document.

How do you print some specific part of a page via window print ()?

How To Print A Page Or Section in Javascript (Simple Examples).
var printwin = window. open("");.
printwin. document. write(document. getElementById("TARGET"). innerHTML);.
printwin. print();.

How do I copy a div in HTML?

Just add the clipboard. js or min file. While initiating, use the class which has the html component to be clicked and just pass the id of the component with the content to be copied, to the click element.