Javascript to print a specific div

I got this code from this site to print a div:

function printData() { var divToPrint=document.getElementById("printTable"); newWin= window.open(""); newWin.document.write(divToPrint.outerHTML); newWin.print(); newWin.close(); } $('button').on('click',function(){ printData(); }) 

How to add CSS code to this javascript to apply to a table with id = 'table'?

 table, td, th { border: 1px solid black; text-align:justify; } th { background-color: #7a7878; text-align:center } 
+5
source share
1 answer

Please take a look at: http://jsfiddle.net/rhjv1u11/

  function printData() { var divToPrint=document.getElementById("printTable"); newWin= window.open(""); newWin.document.write(divToPrint.outerHTML); var css =`table, td, th { border: 1px solid black; text-align:justify; } th { background-color: #7a7878; text-align:center }`; var div = $("<div />", { html: '&shy;<style>' + css + '</style>' }).appendTo( newWin.document.body); newWin.print(); newWin.close(); } $('button').on('click',function(){ printData(); }); 

The example simply inserts a style element containing your rules. If the CSS you need to assign is as small as the example shows (and does not require much maintenance), this is a sufficient solution.

In case it is a lot more complex CSS, you must access newWin.document.head and insert a node to load external CSS. It would look like this:

 var linkElement=document.createElement("link"); linkElement.setAttribute("rel", "stylesheet"); linkElement.setAttribute("type", "text/css"); linkElement.setAttribute("href", "your.css.file.here.css") newWin.document.getElementsByTagName("head")[0].appendChild(linkElement) 
+3
source

Source: https://habr.com/ru/post/1234952/


All Articles