Change the style of element using Jquery

Styles play a big part in the look and feel of any website, and jQuery can help us change them dynamically. In this section, we will look at how jQuery can be used to dynamically add and remove style classes and entire cascading style sheets.



You can change your website’s styles dynamically with jQuery’s .css() function. Either change styles that are already declared inline or in CSS files (such as font-sizecolor,background-color, etc.) or create new styles for elements.

Example: Change text color and background color

$('div#' + id).css({
    'color': 'Blue',
    'background-color': 'orange'


In addition to the .css() function, you can apply currently defined CSS classes by using the .addClass() function. Its counterpart function, .removeClass(), reverses the action.

Example: Add a CSS class to an element

$('#' + id + ' a').addClass('newbutton');

to remove

$('#' + id + ' a').removeClass('jq4ubutton');

The .toggleClass() function is a huge time-saver for toggling a state on and off with CSS. The following example sets event handlers for mouseenter (which applies the CSS classimg-hover to the image) and mouseleave (which removes it).

$('#' + id).live('mouseenter', function (e) {

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s