Save all css properties of element using jquery

2019-03-27 19:25发布

问题:

I'm basically trying to save all current css properties of an element in a local var/array. I tried :

el.css();

and

el.css("*");

With no luck.

Is there any quick tip do to so ?

回答1:

  • demo: http://so.lucafilosofi.com/save-all-css-properties-of-element-using-jquery

i have updated the answer to be more efficent also providing a working demo...

    $(function() {
        // element tag example p and element id
        function get_element_style(element, id){
            var css = {};
            $('<iframe id="get-style-'+id+'" style="display:none"/>').appendTo('body');
            $('#get-style-'+id).contents().find('body').append('</'+element+'>');
            $el = $('#get-style-'+id).contents().find('body').find(element);
            var defaults_css = $el.getStyles();
            $('#get-style-'+id).remove();
            var element_css = $('#'+id).getStyles();
            for (var i in element_css) {
                if (element_css[i] !== defaults_css[i]) {
                    css[i] = element_css[i];
                }
            } 
            return css;
        }

        var properties = get_element_style('p', 'test-p');

    });

the problem when getting the style of an element is that you don't get just setted value but also the default values. with this code i'm trying to get just the setted values of an element. this work both with inline style as well as with <style> and <link>

  • NOTE: this solution require the use of this plugin https://github.com/moagrius/copycss


回答2:

Do you mean:

el.attr('style');

?

Also, this might interest you:

How can I get list of all element css attributes with jQuery?