8

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?

2
  • You mean you want a map with a given set of CSS properties? Commented Feb 13, 2012 at 23:07
  • What do you mean by get multiple css properties? Commented Feb 13, 2012 at 23:08

3 Answers 3

14

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/

Sign up to request clarification or add additional context in comments.

3 Comments

Also, FWIW this method is faster than calling .css() multiple times... who woulda thought? ;) jsperf
@peipst9lker, of course plain JS is faster than jQuery! Though, then you have to hack around browser support (currentStyle vs getComputedStyle). Tradeoffs...
As shown in my answer, working around browser support is trivially easy in this case. It's just as easy as the old e = e || window.event you used to need in manual event handling.
11

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.

Comments

3

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

1 Comment

Yeah, I would have done the same. I just wondered why this isn't already built in. Its just logical, since you can set a single property or set multiple properties. I have automatically assumed you can get a single property and even get multiple properties (would be by passing an array to .css()) but they just seem to forgot it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.