0

This question is similar (I think) to this question on SO: How to move all computed CSS styles from one element and apply them to a different element using JavaScript?

What I want to do is find all styles that have been applied by way of css sheets and set the explicitly (as in using a style= attribute) on the element. The reason I want to do this is so that MS Word (2010) will pick up the styling if I open it there

Here's my code

var $this = $(this);
var styles = window.getComputedStyle(this, null);
$this.css(styles);

I also tried with

var styles = document.defaultView.getComputedStyle(this, null);

When I put a try catch around the last line ($this.css(styles), I am getting an error message "invalid calling object". I don't understand what the problem is

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • 1
    A [CSSStyleDeclaration](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration) is not a plain object as expected by jQuerys [`.css()`](http://api.jquery.com/css/#css-properties) method. – Andreas Jun 26 '18 at 15:52
  • 1
    Could you please specify a reason to do it? – Kosh Jun 26 '18 at 15:54
  • @KoshVery I have added my reason in the question body. It's so that the style shows up in MS Word 2010 – ControlAltDel Jun 26 '18 at 16:04
  • @Andreas understood. So if you can't apply a CSSStyleDeclaration like I am trying, does this make the answer to the "similar" question I referenced incorrect? – ControlAltDel Jun 26 '18 at 16:05
  • @KoshVery to clarify: classes set on paragraphs are showing up in MS Word. But classes on spans are not – ControlAltDel Jun 26 '18 at 16:19

1 Answers1

1

Well, the following snippet does what you want, though I don't think it's what you needed. MS Word is NOT a browser, I'm not sure if it supports all the styles or if jQuery works there...

var $this = $('b');
var styles = window.getComputedStyle($this[0]);

$this.css(
  Object.values(styles).reduce(
    (a, e) => 0*(a[e] = styles[e]) || a, {}
  )
)

console.log(`style="${$this.attr('style')}"`)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<b>I have styles</b>
Kosh
  • 16,966
  • 2
  • 19
  • 34
  • Actually, you are right about "what I need". Stepped away and took lunch, and I realized that the problem could very well be with my CSS formatting... And this is what it is / was! Thank you though for answering the question I asked – ControlAltDel Jun 26 '18 at 17:23
  • @ControlAltDel, happy to help! – Kosh Jun 26 '18 at 17:26