How to copy all user provided styles from one object to another

Question

A question was asked here about how to copy css styles from one object to another. And the generally accepted answer was:

var p = document.getElementById("your_p_id");
var div = document.createElement("div");
div.innerHTML = "your div content";
div.style.cssText = document.defaultView.getComputedStyle(p, "").cssText;

However, my situation is a bit different. I have a script that creates a span to presume a select tag, and then hides the select. This allows for easier CSS styling since I can style the span easier, relative to an adamant select tag.

When I use cssText, to copy any styles applied from the select to the span, it ends up looking like a select tag. Since all inbuilt styles are applied to the span as well rather than just the user input, then I have to override all these css properties by the dozens, which beats the purpose of having a span tag in the first place.

Is there a way to only copy the user provided styles rather than the entire stylesheet used to style an element?

Thus far, I have able to transfer applied styles by transferring the class and id from select to span, but my the challenge is getting styles directly applied on the select tag (ie. in the style/stylesheet, it reads: select { blah : bloh;})


Show source
| javascript   | html   | css   2017-01-03 10:01 1 Answers

Answers ( 1 )

  1. 2017-01-03 13:01

    Try something like this:

    function ApplyStyles(select, span) {
        var select = document.querySelector(select);
        var span = document.querySelector(span);
        var sheets = document.styleSheets;
    
        for(var i = 0; i < sheets.length; i++) {
            var rules = sheets[i].cssRules || sheets[i].rules;   
            for(var r = 0; r < rules.length; r++) {
                var rule = rules[r];
                var selectorText = rule.selectorText;
                if(document.querySelector(selectorText) == select){
            for(var l = 0; l < rule.style.length; l++){
                span.style[rule.style[l]] = rule.style[rule.style[l]];
            }
                }
            }
        }
    }
    

    Then use the function like this:

    ApplyStyles("#selection", "#span");
    

    Here's a JSFiddle for example: https://jsfiddle.net/rsLnaw56/2/

    How this works is it finds all external styles applied to the select element and applies it to the span element.

◀ Go back