Guide on how to print a particular DIV along with its corresponding CSS styling

Is there a way to print a specific DIV in JavaScript while including the styles within it? I have searched through several posts, but haven't found a solution that suits my needs. Is there a single function in JavaScript that can accomplish this?

I have already read through various posts on this topic like Print the contents of a DIV

Answer №1

To hide all elements on the page except for a specific target, you can use the :not() CSS pseudo-class to select and hide them, then trigger the printing of the page by calling window.print():

btn.addEventListener('click', function(){
  document.body.querySelectorAll(':not(.red)').forEach(e => e.style.display = "none");
  window.print();
})
div{
  height:100px;
  border:1px solid;
}
.red{
  background-color:red;
}
.blue{
  background-color:blue;
}
<div class="red">
red
</div>
<div class="blue">
blue
</div>
<button id="btn">Print Red div</button>

If you need to create a function that takes an element as an argument, you can iterate through all elements and compare each one to the parameter. If it doesn't match, hide the element:

Demo:

btn.addEventListener('click', function(){
  printWithStyles(document.querySelector('.red'));
})

function printWithStyles(e){
  document.body.querySelectorAll("*").forEach(f => f === e ? '' : f.style.display="none");
  window.print();
}
div{
  height:100px;
  border:1px solid;
}
.red{
  background-color:red;
}
.blue{
  background-color:blue;
}
<div class="red">
red
</div>
<div class="blue">
blue
</div>
<button id="btn">Print Red div</button>

However, the above function hides children of the specified element, which may lead to problems. To avoid this, we can modify the function to check if an element is contained within the specified parameter:

btn.addEventListener('click', function(){
  printWithStyles(document.querySelector('.red'));
})

function printWithStyles(e){
  document.body.querySelectorAll("*").forEach(f => e.contains(f) ? '' : f.style.display="none");
  window.print();
}
div{
  height:100px;
  border:1px solid;
}
.red{
  background-color:red;
}
.blue{
  background-color:blue;
}
<div class="red">
<h1>red</1>
</div>
<div class="blue">
blue
</div>
<button id="btn">Print Red div</button>

To show all hidden elements after printing, a simple method would be:

document.body.querySelector("*").forEach(e => e.style.display="none");

This will reveal any previously hidden elements before printing.

Answer №2

Follow this easy method to achieve the desired outcome!

  $('a.printPage').click(function(){
          $('#report-summary').show();
             window.print();
             return false;
  });
#report-summary {

}
@page { size:  auto; margin: 25mm 25mm 25mm 25mm; } 
@media print {
  #search,
  .printPage {
    display: none !important;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" referrerpolicy="no-referrer"></script>
<div id="report-summary">
Content here ...

</div>
  <div class="printbtn">
    <a class="printPage" href="#">Print Report</a>
  </div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for adjusting the width of an HTML element that is set to position: fixed

<div class="ui-datatable-scrollable-view" style=" width: 100%; position: relative; "> <div class="ui-widget-header ui-datatable-scrollable-header" style="position:fixed;top:50px"> </div> </div> ...

Discovering the Browser Refresh and Close Events in Angular JS: A Comprehensive Guide

Hello, I've attempted using the event below to detect something, but occasionally it doesn't trigger when closing the tab or browser. $window.addEventListener('beforeunload', function(event) { // Your code here }); ...

Comparing timestamps in JavaScript and PHP - what are the discrepancies?

I seem to be having an issue with the inconsistency in count between two timestamps. Upon page load, I set the input value as follows: $test_start.val(new Date().getTime()); //e.g. equal to 1424157813 Upon submitting the form via ajax, the PHP handler sc ...

What provides quicker performance in AngularJS: a directive or one-time binding?

I need to display a static array on a webpage without Angular watching its value. With that requirement in mind, my question is: Which method is faster: using a directive to fetch a scope variable and create an HTML element with this variable as a hard-co ...

Utilize module.exports to export objects containing callback functions

I am currently diving into the world of writing my own modules for nodejs. My goal is to create various objects that I can use throughout my application. Here is the result I am aiming for: //assuming we have a database: Person_table(ID int A_I, NAME var ...

Tips for successfully importing .eot and .woff documents using Babel?

When attempting to start my project, I encountered the following error message (You may need an appropriate loader to handle this file type.) for .eot, .woff, .ttf, and .svg files: ERROR in ./src/styles/fonts/nm/icons/nm-icons.svg?aaf8685e87a6901c76c52d00 ...

What differences occur in JavaScript when the IE Developers Tools are accessed?

When the IE Developers Tools are opened, what changes in terms of running an AJAX application? I am currently investigating a mysterious bug related to PrimeFaces dropdown lists in Internet Explorer. Sometimes these dropdowns do not open when clicked, but ...

Calculate the sum of the products when multiplying two values from every array of objects, using Reactjs/Javascript

I'm currently developing an eCommerce application and need to calculate the total price of items that users have ordered. I have an array named 'orders' which contains all the ordered items, each item has two keys - payablePrice and purchase ...

What is the best method to combine two BufferGeometries into a single BufferGeometry using Three.JS?

Wondering how to combine two buffer geometries into a single THREE.BufferGeometry in ThreeJS? var mergedGeometry = null; geometry = new THREE.CylinderGeometry(10, 10, 10); if (mergedGeometry === null) { mergedGeometry = new THREE.BufferGeometry().fr ...

Only on mobile devices, Material-UI components spill over the screen

Update: This issue is isolated to one specific page. Other pages within the website are displaying correctly. Recently, I developed a web page using React and Material-UI. The main components utilized are Grid and Container. While the layout appears fine ...

Learning how to use arrow functions with the `subscribe` function in

Can someone help clarify the use of arrow functions in TypeScript with an example from Angular 2's Observable subscribe method? Here's my question: I have code that is functional: this.readdataservice.getPost().subscribe( posts =&g ...

Utilize the CSS content property to embed an image without causing it to distort in size

Struggling to swap out one image for another without stretching it? In my demo, I replaced an elephant with a lion using only CSS - no changes allowed to the HTML. Unfortunately, the lion image ends up stretched. Even adding background-size: cover doesn&ap ...

Interactive Gridview feature enables users to rearrange data elements easily by dragging and dropping them into desired

Currently, I am working on a sample project involving the drag and drop functionality of a grid view that allows users to reorder data. My main challenge is figuring out how to retrieve the data from the first column in the order that the user has changed ...

Issue related to conflicting jQuery references and receiving multiple versions of jQuery simultaneously

Despite having only a reference to jQuery version 1.9.1 in the scripts, version 1.8.2 is somehow being added to the solution. The script used to add it is: bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.js")); Althou ...

Changing an object into an array for saving and transforming it back to an array for usage in JavaScript

I am dealing with a unique situation where I have an object created from dynamic checkboxes in Angular. The structure of the object looks like this: {"United States":true,"Canada":true,"Australia":false} While this format works well for storing values, I ...

Utilizing the filter function iteratively within an Angular factory component

I am facing an issue where I have a factory with 2 controllers. The first controller returns an entire array, while the second controller is supposed to return only one item based on a specific filtering expression. I need to extract the last two parameter ...

Whispering form using onblur and onfocus

Seeking assistance with echoing a form that includes multiple input fields. Specifically, I am attempting to utilize onblur and onfocus (refer to the conditions outlined in the code). However, I am encountering an issue where the Javascript function does ...

Is it possible to utilize AND (&&) OR ( || ) operators within the dependency array of React JS?

Is it possible to include the && and/or || operators in the dependency array like this: const isVisible = true const isModified = false useEffect(() => console.log("both are true"), [isVisible && isModified]) Some may consider this to ...

A React component created in a class cannot effectively update its state when using a functional component to pass

I'm currently working on a React project that involves both a Class component and a Functional Component. In my Class component, I have a function that updates the name in its state. The issue arises when I try to pass this function as a property to t ...

Animate your images with a captivating wave effect using SVG animation

I've been working on animations and I have an SVG image that I want to move like a wave continuously. I've tried using GSAP and CSS but still haven't been successful. Can anyone offer any suggestions or help? It would be greatly appreciated. ...