Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save all css properties of element using jquery

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 ?

like image 418
pixelboy Avatar asked May 03 '10 13:05

pixelboy


2 Answers

  • 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
like image 73
Luca Filosofi Avatar answered Oct 18 '22 22:10

Luca Filosofi


Do you mean:

el.attr('style');

?

Also, this might interest you:

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

like image 26
karim79 Avatar answered Oct 18 '22 22:10

karim79