Using objects in jQuery's .css()

Something I will be focusing on on a regular basis here at JSP is producing tidy code that’s easier to maintain in the future as well as nicer to work with. One such area where people often produce messy code is when using jQuery’s .css() method.

Basic usage of this goes like so:

$(elem).css("display"); //returns value
$(elem).css("display", "block"); //sets value

And in order to set multiple values, people will often do this:

	.css("display", "block")
	.css("border", "1px solid blue")
	.css("background", "#F00")
	{and so on}

However this is the wrong way to do this, on so many levels. jQuery is written pretty cleverly, and .css() can take an object of properties & their respective values:

	"border" : "1px solid blue",
	"display" : "block",
	"background" : "#F00"

It’s worth noting that you don’t actually need the quotes around the properties (but you do around the values), this would be valid:

	border: "1px solid blue",
	{so on}

However, you have to use quotes if you want to use a reserved word as a property. For example if you were creating a new element & setting the class attribute:

$("<div/>", {
	class: "myDiv"

That’s invalid, as class is a reserved word, so you’d have to do :

$("<div/>", {
	"class" : "myDiv"

Because this always trips me up, I’ve simply gotten into the habit of always putting quotes around my property names in JS objects. This is more a personal preference than anything else, just pick what makes the most sense to you.

Don't miss my latest course, React in Five! This course will help you level up your React skills by covering lesser known parts of the React API. Each video is less than five minutes long, and the first four are free to watch. Get started now.

Subscribe to keep up to date with the latest content.

Join the JS Playground mailing list to be kept up to date with the latest tutorials, screencasts and more. You won't be spammed and you can unsubscribe at any time.

Headshot of Jack Franklin

Jack is JavaScript and React developer in London. He's also a keen Elm enthusiast, conference speaker and tweets far too often.