Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
300 views
in Technique[技术] by (71.8m points)

javascript - How to hide element using Twitter Bootstrap and show it using jQuery?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The right answer

Bootstrap 4.x

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>
  • To show it: $("#myId").removeClass('d-none');
  • To hide it: $("#myId").addClass('d-none');
  • To toggle it: $("#myId").toggleClass('d-none');

(thanks to the comment by Fangming)

Bootstrap 3.x

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>
  • To show it: $("#myId").removeClass('hidden');
  • To hide it: $("#myId").addClass('hidden');
  • To toggle it: $("#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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...