title: Javascript - toggle print stylesheet dynamically before window.print()
body: <p>I want to implement a button to print only a certain div of my page while leaving the possibility to the user of printing the entire page. I am using this code for the print stylesheet which works fine so far: <a href="https://stackoverflow.com/questions/468881/print-div-id-printarea-div-only">Print &lt;div id=printarea&gt;&lt;/div&gt; only?</a></p>
  
  <p>Now what I am doing is including a separate stylesheet that only contains the print configuration as suggested here: <a href="https://stackoverflow.com/a/18497062/5775547">https://stackoverflow.com/a/18497062/5775547</a> , and toggle the stylesheet that contains my @media print in the onclick function of my button:</p>
  
  <pre><code>function handlePrintRouteInstructionsClick() {
      routeInstructions.show();
      $('link[id="printCss"]').prop("href", "css/printRouteInstructions.css");
      window.print();
      $('link[id="printCss"]').prop("href", "");
  }
  </code></pre>
  
  <p>The css is included like this:</p>
  
  <pre><code>&lt;link rel="stylesheet" type="text/css" href="" id="printCss" media="print"/&gt;
  </code></pre>
  
  <p>Now when I press the button, it still prints the entire page. Interestingly, when pressing the button a second time, it works just as expected, printing only the specified div. The dialogue triggered by Ctrl+P still prints the entire page, as it should.
  Any ideas why this does not work properly on the first button push?</p>