Reputation: 23978
I have assigned an element a class which has following CSS:
.cls {
display:none !important;
}
When I try to show this element with jQuery
$(".cls").show();
It does not work.
How can I show this element?
Upvotes: 32
Views: 44795
Reputation: 71
Although question has been asked long back but its still relevant for new coders/beginners. Generally this situation comes when you have already applied some class which overriding the display
behavior using !important
property.
Other answers are also relevant to the question and its a matter of achieving the same goal with different approach. I would recommend to achieve it using already available classes in the same library (bootstrap here), instead of writing custom class as these days when most of us are using Bootstrap classes to build the layout.
<div id='container' class="d-flex flex-row align-items-center">
.....
</div>
If you see in the above code, we are using d-flex
class for setting display property of this container. Now if I am trying to show/hide
this container using
$('#container').show()
$('#container').hide()
It will not work as per expectation because of
d-flex
is already using !important
propertyshow()
method will add display:block
not display:flex
to the css property of container.So I will recommend to use hidden
class here.
$('#container').removeClass('hidden')
$('#container').addClass('hidden')
Upvotes: 7
Reputation: 6146
Just had this exact issue, here's what I did first, I added another class to the element, such as:
<div class="ui-cls cls">...</div>
Then in the javascript:
$('.ui-cls').removeClass('cls').show();
The nice thing is that you can also have this code to hide it again:
$('.ui-cls').hide();
and it doesn't matter how many times you hide/show, it'll still work
Upvotes: 1
Reputation: 2783
If the only property in the CLS class selector is the display one, you can do this and don't need to add any extra classes or modify the inline style.
To show them:
$('.cls').removeClass("cls").addClass("_cls");
To hide them:
$('._cls').removeClass("_cls").addClass("cls");
Upvotes: 1
Reputation: 10512
!important; remove all rules and apply the css desfined as !important;. So in your case it is ignoring all rules and applying display:none.
So do this:
.cls {
display:none
}
See this also
Upvotes: 1
Reputation: 6996
2 ways of doing this,
1) Remove the !important
from your .cls
class,
.cls{
display: none;
}
But I assume, you'd have used this elsewhere so it might cause regression.
2) What you could alternatively do is, have a another class and toggle that,
.cls-show{
display: block !important;
}
And then in your javascript,
$('.cls').addClass(".cls-show");
Then when you need to hide it again, you can,
$('.cls').removeClass('.cls-show');
This will help you keep your markup clean and readable
Upvotes: 5