Home  >  Article  >  Web Front-end  >  How can I Print Specific HTML Elements on Button Click without Printing the Entire Page?

How can I Print Specific HTML Elements on Button Click without Printing the Entire Page?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-26 21:42:03630browse

How can I Print Specific HTML Elements on Button Click without Printing the Entire Page?

Print HTML Element on Button Click without Printing the Page

In this scenario, you seek a method to print HTML content triggered by a button click without capturing the entire web page in the print output. Consider the following solution:

CSS Print Media Rule

Using the CSS print media rule, you can selectively display content solely for printing purposes. Here's how you can implement this:

<code class="css">/* CSS file */

@media print {
  /* Hide any element you don't want to print */
  .noPrint {
    display: none;
  }

  /* Set elements you want to print to display */
  h1 {
    color: #f6f6;
  }
}

/* Elements in the HTML page */

<h1>
  Print me
</h1>
<h1 class="noPrint">
  No print
</h1>
<button onclick="window.print();" class="noPrint">
  Print Me
</button></code>

Explanation

  • The @media print rule defines styles specific to the print media.
  • Elements with the noPrint class will be hidden when printing (using display: none).
  • The

    element containing the content you want to print is set to display in the print media and has a distinctive color.

  • When the "Print Me" button is clicked, window.print() is called to print the modified page, which now only includes the desired elements.

Advantages

  • Avoids printing unwanted content.
  • Maintains a clean and uncluttered print output.
  • Allows for flexible content control, ensuring only relevant information is printed.

The above is the detailed content of How can I Print Specific HTML Elements on Button Click without Printing the Entire Page?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn