NOTE: As of July 12, 2009, this blog has been discontinued and replaced by the new Thought Delimited blog. All of the entries in this blog can be found there, along with new posts.

Changing Individual CSS Styles with jQuery

Back when I was writing my own custom JavaScript functions, I learned that there wasn't a single, simple way to change the individual style settings (like "font-weight:bold") for an HTML element that worked on every browser. My solution was to change the CSS classes assigned to the element instead: I wrote a library function that would allow me to add, remove, or replace any class assigned to an HTML element and simply created as many class definitions as I needed in order to accommodate the style changes. It was actually a pretty effective workaround because it let me effectively change multiple styles with one function call.

When I started using jQuery, I quickly learned about the "addClass" and "removeClass" core functions, which I could use instead of my library function:

$("#missionStatement").addClass("importantTextClass");
$("#userProfile").removeClass("hideTextClass");

...So I continued with my routine of changing styles by changing classes, even though sometimes I only needed to change or remove a single style setting. No harm, no foul.

But changing classes wouldn't work for the wacky little project I've been working on recently: I needed to be able to change several styles for an HTML element individually, and writing a class to handle every permutation of the possible style combinations was impractical.

So I went to the jQuery web site, hopeful that the brilliant folks at jQuery had something that could help me out.

And they did: the "css" core function allows you to read or set any individual style or styles:

if ($("#missionStatement").css("font-weight")== "400" || $("#missionStatement").css("font-weight")== "normal")
{
$("#userProfile").css("display","none");
$("#missionStatement").css({ fontSize:"24px", fontWeight:"bold" });
}

Have I mentioned that I love jQuery? :)

Comments
This is exactly the info I needed to solve a problem I'm having. Thank you!
# Posted By Cathy | 5/29/09 12:13 PM
This rocks! Thank you so much for posting this, I have been monkeying with changing a style for a few hours, did not realize you could do it natively in jQuery... this did the trick!
Thank you!
~ Jim Summer
~ Jacksonville, FL
# Posted By Jim Summer | 7/16/09 11:52 AM
Here's one that changes the style of some html elements using the jquery ui slider and a mysql database. http://tympanus.net/codrops/2009/09/06/dynamically...
# Posted By Tim Gray | 9/6/09 7:09 AM
thanks a million, works like a charm
# Posted By razvan | 12/29/09 9:26 AM
BlogCFC was created by Raymond Camden. This blog is running version 5.1.004.