0

Suppose I have the following HTML snippet:

<style>
#testSubject{
  color: red;
  width: 200px;
}
</style>

<p id="testSubject">Hello, world!</p>

With jQuery / vanilla JS, is there any way to save the currently active styling of the element to a variable, so that it may be restored/used later?

ie: var testSubjectStyles = $('#testSubject').css('*');

now I have the variable testSubjectStyles, and can apply those stylings to any element.

Is it possible to do this? I've been playing around with jQuery's .css(), but that only seems to let you set stylings.

tdc
  • 5,174
  • 12
  • 53
  • 102

3 Answers3

0

You could use var yourvar=element.css(); to get an object containing all element specific standard markup. If you also need vendor markup, check out this more complex solution:

Taken from Here

function getStyleObject(stobj){
        var dom = stobj.get(0);
        var style;
        var returns = {};
        if(window.getComputedStyle){
            var camelize = function(a,b){
                return b.toUpperCase();
            };
            style = window.getComputedStyle(dom, null);
            for(var i = 0, l = style.length; i < l; i++){
                var prop = style[i];
                var camel = prop.replace(/\-([a-z])/g, camelize);
                var val = style.getPropertyValue(prop);
                returns[camel] = val;
            };
            return returns;
        };
        if(style = dom.currentStyle){
            for(var prop in style){
                returns[prop] = style[prop];
            };
            return returns;
        };
        return stobj.css();
    }

Then just use var yourstyle=getStyleObject(source);

Community
  • 1
  • 1
René Roth
  • 1,979
  • 1
  • 18
  • 25
0

Suppose you have to get backgroundColor of an element and apply it to another element

var testSubjectStyles = $('#testSubject').css('backgroundColor');
$("#anotherelement").css('backgroundColor',testSubjectStyles);

Hope this helps!

Sagi_Avinash_Varma
  • 1,489
  • 11
  • 23
-1

You can do it with JavaScript, you don't need to use jQuery.

var testSubjectStyles = $('#textSubject')[0].style;

That will give you a full CSSStyleDeclaration object, which includes all the css properties for the element.

user3417400
  • 341
  • 2
  • 4