CSS HTML

How to hide or show a div in HTML?

February 22, 2022

How to hide or show a div in HTML?

In this article we will learn the ways to hide or show a div in HTML – using JavaScript with events or CSS rules.

hide or show a div in HTML cover

What’s up programmers? Let’s learn more about HTML, CSS and JS!

There are two widely used ways to hide and show HTML <divs>:

  • CSS Rules;
  • Handling an event by styling the div;

Ultimately even the way through JavaScript, it becomes a CSS styling application

Let’s see in practice the two possibilities

Hide/Show a div with CSS

The idea here is that we have a div in our HTML code, and we are going to apply a CSS rule to it to hide it.

For this we have to use the display property and the value none

See the code:

<div class="container">
 <p>This element is hidden!</p>
</div>

Notice the div with the container class is what we’re going to access and add the rule

See the necessary code:

.container {
 display: none;
}

So you will hide the div of your page, if you want to show it again, change none to block or delete this rule

Hide/Show a div with JavaScript

To change the style or display of the div with JavaScript, it is necessary to access the element via DOM (Document Object Model)

And change its display property to none or block, as we need

Let’s create a button to make the event:

<div class="container">
 <p>This element is hidden</p>
</div>
<button id='btn-div'>Hide/show div</button>

And our JavaScript code will look like this:

var btn = document.getElementById('btn-div');
var container = document.querySelector('.container');

btn.addEventListener('click', function() {
 if(container.style.display === 'block') {
  container.style.display = 'none';
 } else {
  container.style.display = 'block';
 }
});

Then we map the button in a variable and access the display property of the .container in the click event

If it is visible, it will be hidden and if it is visible, it will be displayed.

This way we can hide or show a div with JS

Conclusion

In this article we learned how to hide/show a div in HTML

Basically we need to access the display property of the target element

Either by CSS or JavaScript and change it to block if we want to display it or to none if we want to hide it

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x