How to set multiple CSS style using jQuery
In last post, I had explained how to select multiple element in single statement using jQuery. In this post, I will show you how can you set multiple CSS styles to any selector/element in single statement.
Let's say you have a div tag and you want to set its background color to yellow, forecolor to red, font family to arial and font size to 18pt. One way is to write multiple statements like.
$(document).ready(function(){ $("#dvText").css('background-color','#FFFF00'); $("#dvText").css('color','#FF0000'); $("#dvText").css('font-family','Arial'); $("#dvText").css('font-size','18pt'); });
But there is another nice way to do this. See below jQuery code.
$(document).ready(function(){ $("#dvText").css({ 'background-color':'#FFFF00', 'color':'#FF0000', 'font-family':'Arial', 'font-size':'18pt'}) });
jQuery provides another nice way to set multiple CSS style together using an object literal. Object literal provides grouping of key/value pair. We can define object literal in curly braces. Key and value pair are defined with the help of colon like Key:Value and multiple keys are separated by comma as defined in above code.
Feel free to contact me for any help related to jQuery. I will gladly help you.