Using JavaScript to Show and Hide a Div
We can use JavaScript to show and hide a div using one button by combing the getElementById() method, the display property, and an if else conditional statement.
We can use JavaScript to show a div and hide a div, but to be able to toggle between the two, we can do so using the code above.
Let’s say we have the following html:
If we want to use JavaScript to show hide the div, we can do so by targeting the element’s display property. We do this simply by getting the id of the div and then changing its display property to “block” if it is hidden, or “none” if it is shown. We check this with an if-else conditional statement.
Note that we can also show/hide (or toggle) a div easily using jQuery with the toggle() method.
Using JavaScript to Show/Hide a Div With a Click
We can use JavaScript to show/hide a div very easily by combining the display property and an if-else conditional statement with an onclick event.
Let’s say that we have the following HTML where we want to give the user the ability to show and hide the div #div1. The div will just be a greenish box that will be shown to start.
Here is the HTML code:
In the JavaScript code, we will add an onclick event to a button that will run a function we will create. In the function, we will simply change the display property of the div to “block” if it is hidden, or “none” if it is shown.
Here is the JavaScript code:
The final code and output for this example of using JavaScript to show/hide a div with a click is below:
Как скрыть html элемент с помощью JS?
Имеется html страница, к которой подключена библиотека jquery, а также один скрипт.
Собственно, на странице реализован механизм, по которому в зависимости от нажатых кнопок меняются элементы на экране. В итоге, после одного из действий, один div блок сменяется другим. В новом div-е имеются различные элементы, некоторые имеют атрибут, прописанный в html — «hidden». Так, в зависимости от различных условий, когда данный div появляется на экране, определенные hidden элементы должны показываться, а показываемые по умолчанию — скрываться. По непонятным причинам, данная часть кода наотрез отказывается работать. Особенно напрягает то, что с другими элементами (те же упомянутые мной div-ы) — все в порядке, я буквально копирую команду на отображение, меняя лишь ID элементов — эффекта ноль. Ниже привожу html код div-а и часть кода скрипта js:
Жирным я выделил то, где имеется проблема. Могу заметить, что условия выполняются корректно — прописанный alert появляется как надо. Также думал о том, чтобы заменить два элемента одним и работать с innerHtml текстом, или менять кавычки с двойных на одиночные (смех смехом, а у меня так innerHtml не работал с двойными, а с одиночными — вполне) или выбирать элемент с помощью средств jQuery — результат тот же, безуспешный. В общем, ситуация сводит сума, возможно, дело в какой-то мелочи, как это обычно бывает, но ничего не выходит. Крайне прошу помочь, заранее благодарю!
Hide and Show a Div Using Javascript
This tutorial will show you how to create a hidden Div and display it with the click of a link. There are a few reasons you may want to hide a Div in a website design. You may want to create a drop down type menu or a box that will show more information when you click a link. Another reason would be for SEO purposes. In theory hiding information in a Div is not against Google’s rules. As long as the user can still see the content when clicking a button you are not displaying different information to the user than you are to the search engine.
First we are going to start with a very basic page layout and create a 2 Divs. One will be shown and one will be hidden. Here is the starting code.
The page should look like this so far.
Now to hide the div. To do this we will change the display to none in the CSS for the #hidden div. See the code below.
Now when you preview the page you will not see the Div.
In order to show the div we will need to add a Javascript function. We will pass the ID attribute of the Div to the function. Basically this means that we can use this one function to show or hide more than one Div on the same page. Below is the Javascript code that we will add the the Head section of the page.
The script above is creating the function “toggle” an passing the value “id”. Next we are using the Document Object Model to get the current state of the display attribute. Then if “display: block;” for the #hidden div we will change it to be “display: none;” else we will change the display to none.
Add the code to your page in the head just below the style.
Now all we have to do is create a link that will call the toggle function and pass the ID of the Div we want to toggle. We will create a link that goes no where and add the onclick property below.
Add the link to your visible div.
Save the file and test. You should not see the Div when the page loads. When you click the toggle link the hidden box will appear.
Here is an example of something you could use this for. I have a site for deals on clothing. Now if we wanted to add some quality SEO content to help the site rank we could put it in a hidden div so that it doesn’t distract the customer.
When the div is clicked it could expand with SEO rich content and links.
I know the tutorial was pretty basic, but I hope that the example above gives you an idea of how this can be used. I may also expand this into another tutorial and show you how to create a nice menu using the technique.
Disclaimer
This site earns money from ads and affiliate links. If you click on a link to a product we may make a small commission on your purchase. Thanks for supporting us.
How to hide and show DOM elements using JavaScript
There are multiple ways to show or hide DOM elements in vanilla JavaScript. In this article, we shall look at two ways to hide or show DOM elements using JavaScript.
The style display property is used to set and get the element's display type in JavaScript.
Majority of the HTML elements have the inline or block display type. The content of an inline element floats to its left and right sides. Block HTML elements are different because they * fill* the entire line and do not show content on their sides.
To hide an element, set the display property to none :
To show an element, set the display property to block (or any other value except none ):
Another way to show or hide DOM elements in JavaScript is using the style visibility property. It is similar to the above display property. However, if you set display: none , it hides the entire element from the DOM. The visibility:hidden hides the element contents, and the HTML element stays in its original position and size.
To hide an element, set the visibility property to hidden :
To show the element again, set the visibility property to visible like below:
The style visibility property only hides the element but doesn't remove the space occupied by the element. If you also want to remove the space, set display: none using the display property.
jQuery provides hide() , show() , and toggle() utility methods that use inline styles to update the display property of the element.
Let us use the style property to create the above jQuery methods in vanilla JavaScript:
Now to hide or show any DOM element, use the above methods:
Notice the use of the getComputedStyle() method, which we just learned the other day, to check if an element is already visible.
We used this method because the style property only deals with inline styles specified using the element's style attribute. But the HTML element could be hidden through an embedded <style> element or an external stylesheet. The getComputedStyle() method returns the actual CSS styles used to render an HTML element, regardless of how those styles were defined.
Another thing to notice is the getComputedStyle(elem).display !== 'none' statement. We are not checking whether the display type is block because block is not the only way to show an element. You could use flex , inline-block , grid , table , etc., for the display property to show an element. However, to hide an element, there is only one value, display: none .
If you prefer to use a CSS class to hide and show DOM elements instead of inline styles, read this guide.
✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.