Remove style added with . css() Function with jQuery

Asked

Viewed 1,015 times

4

I’m changing CSS with jQuery and need to remove the style I added:

if(cor != 'ffffff') $("body").css("background-color", cor); else // remover style ?

The line above runs whenever a color is selected using a color selector, when the mouse moves over a color wheel.

I cannot do this with css, with "background-color", "None" because it will remove the default style of css files. I just want to remove the inline style of background color added by jQuery.

3 answers

1

Leave transparent can solve the problem.

$(document).ready(function(){
    $('ul > li').on('click', function(){
      var cor   = $(this).data('cor');
      var body  = $('body');
      
      body.css('background-color', cor);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body></body>

<ul>
<li data-cor="#FF0000">Cor 1</li>
<li data-cor="#FFFF00">Cor 2</li>
<li data-cor="#0000FF">Cor 3</li>
<li data-cor="#00FF00">Cor 4</li>
<li data-cor="transparent">Nenhuma</li>
</ul>

1

You can change the property to an empty string, to do this:

$("body").css("background-color", "");

Or remove the full attribute, the problem would be that all inline styles of the element would be removed:

 $("body").removeAttr("style");

1

There are several ways to remove a CSS property using jQuery:

1. Setting the CSS property to its default value (initial)

.css("background-color", "transparent")

See the initial value for CSS property in MDN. Here, the value standard is transparent. You can also use inherit for several CSS properties to inherit the attribute from your parent. In CSS3 / CSS4, you can also use initial, revert or unset, but these keywords may have limited browser support.

2. Removing the CSS property

An empty string removes the CSS property:

.css("background-color","")

3. Removing any style from the element

.removeAttr("style")

Browser other questions tagged

You are not signed in. Login or sign up in order to post.