Home >Web Front-end >JS Tutorial >How Can I Easily Print the Content of a DIV Element in JavaScript?

How Can I Easily Print the Content of a DIV Element in JavaScript?

Linda Hamilton
Linda HamiltonOriginal
2024-12-15 08:14:12992browse

How Can I Easily Print the Content of a DIV Element in JavaScript?

Print DIV Content with Ease

Printing the contents of a DIV is a common task encountered in web development. Here's an effective solution to this challenge:

Solution:

The provided JavaScript function, PrintElem, offers a comprehensive approach to printing DIV content with slight modifications for enhanced compatibility with modern browsers like Chrome:

function PrintElem(elem) {
  // Open a new window for printing
  var mywindow = window.open('', 'PRINT', 'height=400,width=600');

  // Write HTML structure to the new window
  mywindow.document.write(`<html><head><title>` + document.title + `</title></head>`);
  mywindow.document.write('<body >');
  mywindow.document.write('<h1>' + document.title + '</h1>');

  // Insert the DIV's innerHTML into the new window
  mywindow.document.write(document.getElementById(elem).innerHTML);

  // Complete the HTML structure and close the window
  mywindow.document.write('</body></html>');
  mywindow.document.close(); // Essential for IE >= 10

  // Focus and print the window
  mywindow.focus();
  mywindow.print();
  mywindow.close();

  return true;
}

Usage:

To print the contents of a DIV with id "myDiv", simply call the PrintElem function as follows:

PrintElem('myDiv');

The above is the detailed content of How Can I Easily Print the Content of a DIV Element in JavaScript?. 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