How to copy all user-created styles from one object to another

The question here is 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 little different. I have a script that creates spanto guess a tag selectand then hides it select. This simplifies CSS styling, as I can simplify the style spanwith respect to the adamant tag select.

When I use cssTextto copy any styles applied from select to range, it looks like a select tag. Since all inline styles also apply to a range, and not just to user input, then I have to override all these css properties with dozens, which exceeds the goal of having a span tag in the first place.

Is there a way to copy only user-created styles, and not the entire stylesheet used to style an element?

I could transfer application styles, passing still classand idfrom select to span, but my goal - to get the styles directly applied to the tag select(ie style / stylesheet, it reads: select { blah : bloh;})

+4
source share
1

- :

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]];
        }
            }
        }
    }
}

:

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

JSFiddle, : https://jsfiddle.net/rsLnaw56/2/

, , select, span.

+1

Source: https://habr.com/ru/post/1665591/


All Articles