CSS style to inline style via JavaScript

You can do something like this:

function applyStyle(el) {
    s = getComputedStyle(el);

    for (let key in s) {
        let prop = key.replace(/\-([a-z])/g, v => v[1].toUpperCase());
        el.style[prop] = s[key];
    }
}

let x = document.getElementById('my-id');
applyStyle(x);

Where x is the element you want to apply the style to.

Basically this function gets the computed style of the element and then copies each property (like padding, background, color, etc.) to the inline style of the element.

I don't know why you need to do this, but it's a really dirty approach in my opinion. I would personally advise against it.


It appears this library will do what you're looking for: https://github.com/lukehorvat/computed-style-to-inline-style

Convert a HTML element's computed CSS to inline CSS.

Uses Window.getComputedStyle internally.