1

I need to format a document differently when it is printed. Basic stuff, media print vs. screen, however this particular webpage is getting some inline styles inserted dynamically. How do I strip them before sending to print?

I am adding an element with jQuery, which is not visible on the screen but appears in print (#myElement). So I've attempted to piggyback on that element but did not really succeed.

if ($('#myElement').is(':visible')) {
    $('.myContent').attr('style', '');
}

What am I missing?

Thanks.

santa
  • 12,234
  • 49
  • 155
  • 255
  • You can use either `$('div[style]').removeAttr('style');` or `$('div').removeAttr('style');`, the former of which is quicker. See [here](http://stackoverflow.com/questions/1229688/how-can-i-erase-all-inline-styles-with-javascript-and-leave-only-the-styles-spec) – royhowie May 06 '14 at 21:26
  • Where is the page getting the dynamically inlined style from? If that's your own code, then maybe you can change it to dynamicly added classes for which the style in in the (external) CSS. That also allows you to use the `@print` medium again. – GolezTrol May 06 '14 at 21:31
  • No, it's not my page and I can't change that. I'm starting to think I may not be checking if the media is correct properly. I assumed it was correct, because I did this logic toggle if / else. Else was true but it could've been true even if IF was wrong... What is the sure way to include code to execute only for print? – santa May 06 '14 at 21:35

1 Answers1

0

Here is an example of how you might do this with regular, vanilla JS: http://jsfiddle.net/AfdzW/. Basically you just need to target whichever DOM elements whose inline styles you wish to remove and call the removeAttribute() method on them.

function clearInlineStyles(sel) {
  var els = document.querySelectorAll(sel);
  [].forEach.call(els, function(e) {
    e.removeAttribute('style'); 
  });
}

clearInlineStyles('div');

As an alternative, if you only wish to target certain inline styles, you can use the $.fn.css() jQuery method to target those styles individually:

$.fn.removeSelectedStyles = function() {
  var styles = arguments;
  this.each(function() {
    var $that = $(this);
    [].forEach.call(styles, function(style) {
      $that.css(style, '');
    });
  });
}

$('div').removeSelectedStyles('background', 'height');

Here's a fiddle demonstrating the jQuery plugin at work

wvandaal
  • 4,265
  • 2
  • 16
  • 27