How to print content inside an HTML div?


I have a page and in it the content I want to print.

I created a command in JavaScript, but this command makes the whole page print.

Is there any way to print only the contents of a div ?

asked by Felipe Goulart 21.12.2013 в 04:20

5 answers


It is not possible to select a div for printing with JavaScript, because this is not a function of it. There is a solution that uses only CSS:

@media print {
  body * {
    visibility: hidden;
  #printable, #printable * {
    visibility: visible;
  #printable {
    position: fixed;
    left: 0;
    top: 0;

In this way, only what is inside this printable element in HTML will be displayed.

21.12.2013 / 04:36
var conteudo = document.getElementById('sua_div').innerHTML,
    tela_impressao ='about:blank');


This code should only be executed when triggering some mouse event, otherwise the popup blocker will block the action.

It works very well. Test!

Fiddle: link

21.12.2013 в 19:09

In short:

function cont(){
   var conteudo = document.getElementById('print').innerHTML;
   tela_impressao ='about:blank');

<div id="print" class="conteudo">
// conteúdo a ser impresso pode ser um form ou um table.

<input type="button" onclick="cont();" value="Imprimir Div separadamente">
26.11.2014 в 15:23
  function printDiv(divID) {
        //pega o Html da DIV
        var divElements = document.getElementById(divID).innerHTML;
        //pega o HTML de toda tag Body
        var oldPage = document.body.innerHTML;

        //Alterna o body 
        document.body.innerHTML = 
          "<html><head><title></title></head><body>" + 
          divElements + "</body>";

        //Imprime o body atual

        //Retorna o conteudo original da página. 
        document.body.innerHTML = oldPage;


And you can also use a popup.

    function printDiv(divID)  
        var conteudo = document.getElementById(divID).innerHTML;  
        var win =;  
        win.close();//Fecha após a impressão.  
21.12.2013 в 15:16

The solutions presented above are not as flexible. They have at least one of the listed problems:

  • Does not support printing large content that gives more than one sheet
  • Remove all CSS already rendered

Here is my solution using jQuery:

JS Code:

function printBy(selector){
    var $print = $(selector)

    // Stop JS execution

    // Remove div once printed

CSS style:

@media print {
    html, body {
        margin: 0;
        padding: 0;
        border: 0;
    #printable {
        margin: 0;
        padding: 0;
        border: 0;
        font-size: 14px;
    #printable ~ * {
        display: none;
03.05.2017 в 20:19