How to restore CSS styles using jQuery

To assign inline css to any DOM element, we can jQuery ".css()" method to define it. Like,

$("#dvText").css('color','#FF0000');

And if you need to remove the color again, then you can use the same css method to remove it. Like,

$("#dvText").css('color','');

The above method to remove/restore the style is fine, when you have defined a single inline css class. If you have defined multiple CSS styles like,

$(document).ready(function(){
  $("#dvText").css('background-color','#FFFF00');
  $("#dvText").css('color','#FF0000');
  $("#dvText").css('font-family','Arial');
  $("#dvText").css('font-size','18pt');
});

Or using CSS method to combine multiple CSS styles.

$("#dvText").css({
  'background-color':'#FFFF00',
  'color':'#FF0000',
  'font-family':'Arial',
  'font-size':'18pt'})

In this case, you need to write same number of statement to remove/restore all the CSS styles which defined earlier. Is there any simple and slick way to do this?

Yes, there is. But first understand what actually .css() method does. When .css() method is used, it defines a style attribute to the DOM element. For example,

$("#dvText").css('color','#FF0000');

will be equivalent to:

<div style="color:#FF0000;">...</div>

So, to remove/restore all the defined style attribute, all you need to do is to remove style attribute which you can do via "removeAttr()" method.

$("#dvText").removeAttr("style") ;


Responsive Menu
Add more content here...