CSS Print hide all but one element

I searched the internet for a solution. I want one thing. when using @media print {...} I want to hide all the elements inside the body except one. How to do it? I have class = "print", which I do not want to hide, how to hide everything that does not have this class?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
@media print {
:not(.print) {
    display: none
}
}
</style>
</head>

<body>
<div class="print">
  <p>neki lijepi tekst</p>
  <p> test</p>
</div>
<div id="test"> ovo se ne vidi naa printu </div>
<div id="tesft"> ovo se nedsfdf vidi naa printu </div>
</body>
</html>
+3
source share
2 answers

It depends on your DOM structure.

You want to hide every top level node (and therefore their children) with CSS ( display: none), except for the object you want to print, and every parent element of the specified element (i.e. t want to hide the top level node containing the element you want to print).

() javascript - jQuery .

  • , , , 'printThis'
  • BODY , display: none, 'doNotPrint'
  • , ( 'printThis')
  • DOM , , , (, , hide )

, - , :

// to start, hide all top level nodes
$('body').children().addClass('doNotPrint')

// now we call this function passing in the 
// item to print
function showItem($node) {
    // remove the 'hide' class. This is moot
    // until we loop to the top level node, at
    // which point this takes affect
    $node.removeClass('doNotPrint');
    // we don't want to print the siblings
    // so we will hide those
    $node.siblings().addClass('doNotPrint')
    // now we check to see if this item has a parent
    // and, if so...
    if($node.parent().length){
        // ...we want to show the parent, hide its 
        // siblings, and then continue this process
        // back to the top of the node tree
        showItem($node.parent());
    } 
}

showItem($('.printThis'));

CSS :

.doNotPrint {display: none;}
+4

print

body > * { display: none }
.print { display: block }

bodytis, .

+8
source

All Articles