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

How Can I Effectively Print the Contents of a DIV Element in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-06 19:33:18564browse

How Can I Effectively Print the Contents of a DIV Element in JavaScript?

Printing the Contents of a DIV

Within the realm of web development, displaying information within designated areas is commonplace. However, the need arises to present these contents in a tangible format, such as printed documents. Among the various methods available, let's explore the most effective approach to printing the contents of a DIV.

Solution:

For this purpose, a JavaScript function called PrintElem has proven to be highly effective. This function takes a single element's ID as an argument and initializes a new window exclusively for printing. Within this window, the contents of the specified DIV are meticulously extracted and formatted into a printable HTML document.

function PrintElem(elem) {
  var mywindow = window.open('', 'PRINT', 'height=400,width=600');

  mywindow.document.write('<html><head><title>' + document.title + '</title>');
  mywindow.document.write('</head><body >');
  mywindow.document.write('<h1>' + document.title + '</h1>');
  mywindow.document.write(document.getElementById(elem).innerHTML);
  mywindow.document.write('</body></html>');

  mywindow.document.close(); // necessary for IE >= 10
  mywindow.focus(); // necessary for IE >= 10*/

  mywindow.print();
  mywindow.close();

  return true;
}

This function operates seamlessly on modern browsers, including Chrome. Its effectiveness stems from its versatility in handling elements with complex content, ensuring a visually accurate representation on printed documents. With this technique, developers can effortlessly convert digital information into tangible formats, catering to diverse requirements.

The above is the detailed content of How Can I Effectively Print the Contents 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