Neeraj Tangariya
Neeraj Tangariya

Reputation: 1407

remove class style property using javascript

In my project, I have card-footer class and I want to remove his style background-color property using the javascript. Can anyone tell me what's wrong with this function?

This is my html tag

 <div class="card-footer">
   <a name="" id="" class="btn btn-light" href="{{ route('posts.index') }}" role="button">Cancel</a>
   <button type="submit" class="btn btn-primary float-right">Create</button>
 </div>

script part

   <script>
       (function removeProp()
        {
            const cardFooter = document.querySelector(".card-footer");
            cardFooter.style.removeProperty('background-color');
        })();
    </script>

Did I miss something or else?

Upvotes: 0

Views: 1429

Answers (3)

sandeep joshi
sandeep joshi

Reputation: 2141

if you don't want to use that class and want to update the element with new class rule you can use below code. or you can simply remove the footer class.

 (function removeProp()
        {
            const cardFooter = document.querySelector(".card-footer");
            cardFooter.classList.remove('card-footer');
            // you may add another class to change style and define you custom css class rules which you want to apply to cardFooter.
            cardFooter.classList.add('custom-card-footer');
        })();
.card-footer{
  background-color: yellow;
}
.custom-card-footer{
  background-color: grey;
}
<div class="card-footer">
   <a name="" id="" class="btn btn-light" href="{{ route('posts.index') }}" role="button">Cancel</a>
   <button type="submit" class="btn btn-primary float-right">Create</button>
 </div>

Upvotes: 1

Daniel
Daniel

Reputation: 8647

You can have style assigned to the class or to element.

If you have in css

.card-footer {
   background-color: ...
}

then you need to remove class by:

document.querySelector(".card-footer").classList.remove('card-footer')

You can also find style element in HTML by:

document.querySelector("style").textContent = ... <-- new css without  `background-color` of your `card-footer` class

Simples possible solution is provide two classes with separated responsibility

for example:

.card-footer { all styles out of bg color } 
.card-bg { backgroud-color: ... }

And then remove class by classList interface.

Upvotes: 0

Quentin
Quentin

Reputation: 943108

The style property addresses only rules applied directly to the element (e.g. with the style attribute).

It does not address rules from anywhere else in the cascade.

If you want to modify those, you’ll need to use the CSS Object Model to access the rule set containing them.

Alternatively, if you want to modify the value for a particular element you could set a new value using the style property.

Upvotes: 2

Related Questions