Hide Element When Printing a Web Page



In this article, we will learn to hide an element when printing a web page in JavaScript and HTML. When printing a web page, you can suppress elements such as navigation menus, advertisements, and interactive elements that you do not require on paper and print only the required information.

Different Approaches

The Following are the two different approaches to hiding an element when printing a web page ?

Using CSS Media Query

The most common and efficient method to hide elements during printing is by using the @media print CSS rule. This enables you to specify styles that will only be applied when the page is being printed.

  • Any element with the class no-print will be hidden when the page is printed.
  • This rule only applies when the print dialog is activated.

To hide the element, add "display:none" to the element with CSS ?

<style>
@media print {
   .noprint {
      display:none;
   }
}
</style>

In addition, add the element, which you want to hide inside the <div> ?

<div id="noprint">
   Add here the element, which you want to hide.
</div>

Using JavaScript to Hide Elements Before Printing

For more control, we can hide the elements temporarily before opening the print dialog dynamically using JavaScript.

  • The JavaScript approach hides the element before calling window.print().
  • When printed, the item reverts to its default visibility.

Example

Below is an example of hiding elements before printing in JavaScript ?

<button onclick="printPage()">Print</button>

<div id="hide-before-print">Not appear in the printout.</div>

<script>
function printPage() {
    var ele = document.getElementById("hide-before-print");
    elem.style.display = "none";
    window.print();
    ele.style.display = "block";
}
</script>

Conclusion

Hiding things upon printing a webpage can enhance the readability and inclusion of only related information. Use the @media print CSS statement for the most effective method but JavaScript can serve as an alternate for dynamic manipulation.

Alshifa Hasnain
Alshifa Hasnain

Converting Code to Clarity

Updated on: 2025-03-13T12:04:52+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements