Hulk
Hulk

Reputation: 34200

Printing contents of a div

The contents of the following div is derived dynamically: i.e a table is added dynamically to this div with some button.

My question is how to print the content of this div(window.print) and not other things in the page

<div id="newdiv" name="newdiv"></div>

Thanks.

Upvotes: 0

Views: 1077

Answers (3)

aaaaaaaaaaaa
aaaaaaaaaaaa

Reputation: 3700

Clever thinking Pekka, but it doesn't work quite like that, after using a global display:none you would have to redisplay every single element that needs to be displayed, including all parent elements. Best way would be to hide all the elements that should not be printed, good news is that you only need to hide the parent element and everything in it will be hidden.

There is by the way no need for an extra style sheet, a block in an existing sheet can be used (it must be placed at the end of the last sheet):

@media print{
    .noprint{
        display:none;
    }
}

Now a block can be hidden from printing simply by giving its container the noprint class.

Upvotes: 4

digitaldreamer
digitaldreamer

Reputation: 55532

Your best bet is to create a media-specific style sheet.

http://www.alistapart.com/articles/goingtoprint/

Upvotes: 0

Pekka
Pekka

Reputation: 449783

Two ideas:

  • Introduce a print stylesheet

     <link rel="stylesheet" href="print.css" type="text/css" media="print"  />
    

    that will give every element display: none except for newdiv:

     * { display: none } /* This should hide all elements */
     div#newdiv { display: block } /* This should make newdiv visible again */
    

    I can't test this right now but I can't see why this wouldn't work.

  • Copy the contents of the div into a newly created iframe element using JavaScript and print that.

    Lots of obstacles on the road that way, though. I'd try using CSS first.

Upvotes: 7

Related Questions