jQuery CSS Multi-property getter

May 28th, 2013

How many times have you wanted to get more than one property, say the margin or padding of an element with jQuery? After looking through the jQuery 1.9 release notes I saw that you can now use .css() to get many properties.

Now, apparently being able to set something like the padding short hand was something that you have be able to do for a while.


$('div').css('padding','1em 2em 3em 4em');

As of 1.9 you are now able to get multiple values:


var cssProps = $('div').css(['paddingTop','paddingRight','paddingBottom','paddingLeft']);


This will return an object that would look something like this:


{
     paddingTop: "16px", 
     paddingRight: "32px", 
     paddingBottom: "48px", 
     paddingLeft: "64px"
}

You pass an array into .css() and the value returned is an object that you can than access.

You can of course grab various properties:


var multiProps = $('.first').css(['height','background-color']);

Which will return an object like:


{
     height: "80px", 
     background-color: "rgb(0, 97, 92)"
} 

Jsfiddle here

Which is probably the most exciting thing about it.

As of yet I have not had to use this in production as I have not quite been able to find a use for it, and if you look at the bug tracker for this issue it seems like an actual use case was not quite clear. Damien’s comment about using it to clone an element to a new context seems to be the most appropriate I have found.


Warning: count(): Parameter must be an array or an object that implements Countable in /home/ryanch6/public_html/wp-includes/class-wp-comment-query.php on line 405