CSS style to inline style via JavaScript
Asked Answered
K

5

10

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.

Klutz answered 2/8, 2014 at 17:19 Comment(7)
That is going to be a lot harder than you think, and you shouldn't really need it.Ineluctable
@Ineluctable Trust me, I really need it.Klutz
@doniyor As long as other parts of my script are large, I don't want any external libraries in my page, so no JQuery, please.Klutz
I'm guessing the style is in a stylesheet, so first you have to find the stylesheet or style tag, then you have parse the stylesheet to find the matching selector, then you have to parse all the styles and add them all to the element. Good luck !Ineluctable
@Ineluctable That's not really necessary. I know getComputedStyle does that for me. All I need to do is to get everything from getComputedStyle and put it in element's style. But I can't get it to work.Klutz
Without Jquery this will be even harder than it would be before. Just load Jquery from their CDN and use it. It will make doing this, less hard.Disability
Of course getComputedStyle does that, but then the question makes no sense at all, as getComputedStyle gets all the current styles, and how would that re-write any current styles, or have anything to do with the line of CSS you posted.Ineluctable
B
11

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.

Berns answered 2/8, 2014 at 17:49 Comment(5)
Still not working for me, but I think you're almost there. Honestly, I find this method of rendering any element in canvas really easy, so, for converting any element to svg, I need inline styles. This is what I'm talking about: developer.mozilla.org/en-US/docs/Web/HTML/Canvas/…Klutz
This is another kind of stuff. I'm not familiar with canvas and you asked about a function to make inline any style applied to an element. That's what I did. I can't help you more than this...Berns
That inline style code is all I need. I have written other parts of my code, myself. But your function doesn't seem to work.Klutz
It works, try to run it on this page with the console on the element #answers-header, and you'll see that all the style will be added in the dom. Here is a screenshot: i.imgur.com/3I3REQn.jpgBerns
Yeah! It works! For some reason, it doesn't work for me. Maybe the problem is with my code, but you've earned a +1 anyways. Thanks.Klutz
I
3

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.

Irruptive answered 15/3, 2019 at 21:48 Comment(0)
O
2

This one?

    function transferComputedStyle(node) {
        var cs = getComputedStyle(node, null);
        var i;
        for (i = 0; i < cs.length; i++) {
            var s = cs[i] + "";
              node.style[s] = cs[s];
        }
    }
    function transferAll() {
        var all = document.getElementsByTagName("*");
        var i;
        for (i = 0; i < all.length; i++) {
            transferComputedStyle(all[i]);
        }
    }

Simply call transferAll onload, or whereever.

Outgo answered 2/8, 2014 at 18:13 Comment(0)
C
1

I think the issue with the accepted answer (thank you for that!) is that one of the properties it tries to transfer on the element style from the Computed Style is the cssText.

If we exclude from the transfer cssText and also other properties that are actually methods, it works!

So building on the accepted answer and this answer, I've got:

var el = document.querySelector("#answer-25097808 > div > div.answercell.post-layout--right > div.s-prose.js-post-body > pre"); // change yourId to id of your element, or you can write “body” and it will convert all document
var els = el.getElementsByTagName("*");

for(var i = -1, l = els.length; ++i < l;){
    el = els[i]
    s = getComputedStyle(el)
    for (let styleKey in el.style) {
        for (let computedStyleKey in s) {
            let computedStyleKeyCamelCase = computedStyleKey.replace(/\-([a-z])/g, v => v[1].toUpperCase());
            if ((typeof el.style[styleKey] != "function") && (styleKey != 'cssText')){
                if(styleKey == computedStyleKeyCamelCase) {
                    el.style[styleKey] = s[computedStyleKey];
                }
            }
        }
    }
}

P.S.: the above code should run in the Developer Tools console (tried it in Chrome)

Chromophore answered 11/6, 2021 at 16:49 Comment(1)
Thanks a lot it works in my case, I needed this conversion for building a mail html body with stylesRobb
H
-1

Using jQuery it can be done easily. Here is the sample code:
If you are new in jQuery and you don't know how to add and work then follow this link

$(document).ready(function(){ $("#d").css('background-color', '#444444').css('width', '50px').css('height', '20px').css('display', 'inline-block'); });

For javascript code I am not confident but for jQuery I am sure that it will work.

Correct me if I am wrong.

Headlight answered 2/8, 2014 at 17:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.