Christian Engel
Christian Engel

Reputation: 3778

Get multiple CSS properties with jQuery

I know you can SET multiple css properties like so:

$('#element').css({property: value, property: value});

But how do I GET multiple properties with CSS? Is there any solution at all?

Upvotes: 8

Views: 5278

Answers (3)

bawwb
bawwb

Reputation: 153

jquery's css method (as of 1.9) says you can pass an array of property strings and it will return an object with key/value pairs.

eg:

$( elem ).css([ 'property1', 'property2', 'property3' ]);

http://api.jquery.com/css/

Upvotes: 14

Jasper
Jasper

Reputation: 76003

You can create your own jQuery function to do this: ​

//create a jQuery function named `cssGet`
$.fn.cssGet = function (propertyArray) {

    //create an output variable and limit this function to finding info for only the first element passed into the function
    var output = {},
        self   = this.eq(0);

    //iterate through the properties passed into the function and add them to the output variable
    for (var i = 0, len = propertyArray.length; i < len; i++) {
        output[propertyArray[i]] = this.css(propertyArray[i]);
    }
    return output;
};

Here is a demo: http://jsfiddle.net/6qfQx/1/ (check your console log to see the output)

This function requires an array to be passed in containing the CSS properties to look-up. Usage for this would be something like:

var elementProperties = $('#my-element').cssGet(['color', 'paddingTop', 'paddingLeft']);
console.log(elementProperties.color);//this will output the `color` CSS property for the selected element

Upvotes: 3

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

Easiest way? Drop the jQuery.

var e = document.getElementById('element');
var css = e.currentStyle || getComputedStyle(e);
// now access things like css.color, css.backgroundImage, etc.

Upvotes: 11

Related Questions