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") ;
SHARE

Nothing shocks me, I'm a Software Engineer. And I am not young enough to know everything. I live in World Wide Web and from there take care of this website. This website communicates about my work, learning and experience. I believe life is short, and it is for loving, sharing, learning and connecting. So lets connect..