Let's say I create an HTML element like this,
<div id="my-div" class="hidden">Hello, TB3</div>
<div id="my-div" class="hide">Hello, TB4</div>
<div id="my-div" class="d-none">Hello, TB4</div>
How could I show and hide that HTML element from jQuery/Javascript.
JavaScript:
$(function(){
$("#my-div").show();
});
Result: (with any of these).
I would like the elements above to be hidden.
What is simplest way to hide element using Bootstrap and show it using jQuery?
Bootstrap 4.x uses the new .d-none
class. Instead of using either .hidden
, or .hide
if you're using Bootstrap 4.x use .d-none
.
<div id="myId" class="d-none">Foobar</div>
$("#myId").removeClass('d-none');
$("#myId").addClass('d-none');
$("#myId").toggleClass('d-none');
(thanks to the comment by Fangming)
First, don't use .hide
! Use .hidden
. As others have said, .hide
is deprecated,
.hide is available, but it does not always affect screen readers and is deprecated as of v3.0.1
Second, use jQuery's .toggleClass(), .addClass() and .removeClass()
<div id="myId" class="hidden">Foobar</div>
$("#myId").removeClass('hidden');
$("#myId").addClass('hidden');
$("#myId").toggleClass('hidden');
Don't use the css class .show
, it has a very small use case. The definitions of show
, hidden
and invisible
are in the docs.
// Classes
.show {
display: block !important;
}
.hidden {
display: none !important;
visibility: hidden !important;
}
.invisible {
visibility: hidden;
}