How to print specific HTML content in a new page

Update: if you want to do it easier and in the same page, check this out: How to print a specific HTML element.

If you want to print a specific HTML content, for example everything inside a div tag or a tag element with a particular identifier, you can use window.print() in a new window with just the content you want to. It’s easy but tricky, we would like an accessible print method for any HTML element but there wasn’t.

Don’t forget to add/link some CSS in your new window otherwise you will get the default style from your browser.

Note that write method is synchronous, however sometimes window tries to print before write has finished, it happens only in some browsers ¬¬, therefore trying to avoid this we have added a setTimeout. Yeah, no quite elegant but among all the different ways, it is the shortest that works across all updated browsers so far.