How to Hide and Show a <div>
If you don’t know how to hide and show a <div> element, you should definitely check this tutorial! Hiding and showing a <div> in HTML is quite an easy thing. You can do it with CSS or a small piece of JavaScript and jQuery codes.
The document.getElementById will select the <div> with given id. You should set the display to «none» so as to make it disappear when clicked on <div>:
Another example of hiding and showing div with JavaScript:
Now let’s see how you can hide and show your <div> element with pure CSS using the CSS :hover pseudo-class. Here’s the full code:
When the user hovers over the <div>, it disappears, and the form is displayed.
JavaScript — How to show and hide div by a button click
To display or hide a <div> by a <button> click, you can add the onclick event listener to the <button> element.
The onclick listener for the button will have a function that will change the display attribute of the <div> from the default value (which is block ) to none .
For example, suppose you have an HTML <body> element as follows:
The <button> element above is created to hide or show the <div > element on click.
You need to add the onclick event listener to the <button> element like this:
The HTML will be rendered as if the <div> element never existed by setting the display attribute to none .
When you click the <button> element again, the display attribute will be set back to block , so the <div> will be rendered back in the HTML page.
Since this solution is using JavaScript API native to the browser, you don’t need to install any JavaScript libraries like jQuery.
You can add the JavaScript code to your HTML <body> tag using the <script> tag as follows:
Feel free to use and modify the code above in your project.
I hope this tutorial has been useful for you.
Level up your programming skills
I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!
About
Sebhastian is a site that makes learning programming easy with its step-by-step, beginner-friendly tutorials.
Learn JavaScript and other programming languages with clear examples.
Как скрыть html элемент с помощью JS?
Имеется html страница, к которой подключена библиотека jquery, а также один скрипт.
Собственно, на странице реализован механизм, по которому в зависимости от нажатых кнопок меняются элементы на экране. В итоге, после одного из действий, один div блок сменяется другим. В новом div-е имеются различные элементы, некоторые имеют атрибут, прописанный в html — «hidden». Так, в зависимости от различных условий, когда данный div появляется на экране, определенные hidden элементы должны показываться, а показываемые по умолчанию — скрываться. По непонятным причинам, данная часть кода наотрез отказывается работать. Особенно напрягает то, что с другими элементами (те же упомянутые мной div-ы) — все в порядке, я буквально копирую команду на отображение, меняя лишь ID элементов — эффекта ноль. Ниже привожу html код div-а и часть кода скрипта js:
Жирным я выделил то, где имеется проблема. Могу заметить, что условия выполняются корректно — прописанный alert появляется как надо. Также думал о том, чтобы заменить два элемента одним и работать с innerHtml текстом, или менять кавычки с двойных на одиночные (смех смехом, а у меня так innerHtml не работал с двойными, а с одиночными — вполне) или выбирать элемент с помощью средств jQuery — результат тот же, безуспешный. В общем, ситуация сводит сума, возможно, дело в какой-то мелочи, как это обычно бывает, но ничего не выходит. Крайне прошу помочь, заранее благодарю!
Show/hide 'div' using JavaScript
For a website I’m doing, I want to load one div, and hide another, then have two buttons that will toggle views between the div using JavaScript.
This is my current code
The second function that replaces div2 is not working, but the first one is.
![]()
15 Answers 15
How to show or hide an element:
In order to show or hide an element, manipulate the element’s style property. In most cases, you probably just want to change the element’s display property:
Alternatively, if you would still like the element to occupy space (like if you were to hide a table cell), you could change the element’s visibility property instead:
Hiding a collection of elements:
If you want to hide a collection of elements, just iterate over each element and change the element’s display to none :
Showing a collection of elements:
Most of the time, you will probably just be toggling between display: none and display: block , which means that the following may be sufficient when showing a collection of elements.
You can optionally specify the desired display as the second argument if you don’t want it to default to block .
Alternatively, a better approach for showing the element(s) would be to merely remove the inline display styling in order to revert it back to its initial state. Then check the computed display style of the element in order to determine whether it is being hidden by a cascaded rule. If so, then show the element.
(If you want to take it a step further, you could even mimic what jQuery does and determine the element’s default browser styling by appending the element to a blank iframe (without a conflicting stylesheet) and then retrieve the computed styling. In doing so, you will know the true initial display property value of the element and you won’t have to hardcode a value in order to get the desired results.)
Toggling the display:
Similarly, if you would like to toggle the display of an element or collection of elements, you could simply iterate over each element and determine whether it is visible by checking the computed value of the display property. If it’s visible, set the display to none , otherwise remove the inline display styling, and if it’s still hidden, set the display to the specified value or the hardcoded default, block .