javascriptcssstylesinline

CSS style to inline style via JavaScript


I want to add all CSS styles of a specific element to its inline style attribute. For example:

I have:

 <div id="d"></div>

and:

#d { background: #444444; width: 50px; height: 20px; display: inline-block; }

Now I want a JavaScript function that turns my div into this:

<div id="d" style="background: #444444; width: 50px; height: 20px; display: inline-block;"></div>

Please help me. And, by the way, I don't want any CSS styles to re-write any existing inline style.


Solution

  • 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.