DEV Community

Cover image for Print a div tag content with Javascript.

Print a div tag content with Javascript.

Ariel Mejia on October 23, 2020

Here a simple example of an html template created with TailwindCSS: <!DOCTYPE html> <html lang="en"> <head> <meta chars...
Collapse
 
linehammer profile image
linehammer

var mywindow = window.open();
var content = document.getElementById(elem).innerHTML;
mywindow.document.write(content);
mywindow.print();

In the above code, when you click the button "Print a Div" , a JavaScript popup window is created and extracted the contents of the HTML div elements to store it in a JavaScript variable. Then the contents of the HTML div elements are written to the popup window and finally the window is printed using the JavaScript Window print() command.

net-informations.com/js/progs/prin...

Collapse
 
kissa1001 profile image
Lina Nguyen

this script doesnt work when you click the button second time :(

Collapse
 
arielmejiadev profile image
Ariel Mejia

if you can share the code I can test it.