11

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.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
vahidseo
  • 371
  • 1
  • 3
  • 16
  • 2
    That is going to be ***a lot*** harder than you think, and you shouldn't really need it. – adeneo Aug 02 '14 at 17:20
  • @adeneo Trust me, I really need it. – vahidseo Aug 02 '14 at 17:23
  • @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. – vahidseo Aug 02 '14 at 17:24
  • 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 ! – adeneo Aug 02 '14 at 17:27
  • 1
    @adeneo 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. – vahidseo Aug 02 '14 at 17:29
  • 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. – Noah Huppert Aug 02 '14 at 17:31
  • 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. – adeneo Aug 02 '14 at 17:40

5 Answers5

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.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
  • 1
    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: https://developer.mozilla.org/en-US/docs/Web/HTML/Canvas/Drawing_DOM_objects_into_a_canvas – vahidseo Aug 02 '14 at 18:01
  • 1
    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... – Marco Bonelli Aug 02 '14 at 18:11
  • 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. – vahidseo Aug 02 '14 at 18:13
  • 1
    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: http://i.imgur.com/3I3REQn.jpg – Marco Bonelli Aug 02 '14 at 18:18
  • 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. – vahidseo Aug 02 '14 at 18:25
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.

Community
  • 1
  • 1
Venryx
  • 15,624
  • 10
  • 70
  • 96
1

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.

atmin
  • 370
  • 1
  • 7
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)

ams1
  • 113
  • 8
-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.

Community
  • 1
  • 1
Avoid
  • 343
  • 2
  • 9
  • 20