How to Hide and Show Element in JavaScript Easily
Use the
style.display property to hide or show an element in JavaScript. Set element.style.display = 'none' to hide and element.style.display = 'block' (or other display types) to show it again.Syntax
To hide or show an element, access it via JavaScript and change its style.display property.
element.style.display = 'none'hides the element.element.style.display = 'block'(orinline,flex, etc.) shows the element.
javascript
element.style.display = 'none'; // hides the element element.style.display = 'block'; // shows the element
Example
This example shows a button that toggles the visibility of a text paragraph by changing its display style.
javascript
const btn = document.getElementById('toggleBtn'); const text = document.getElementById('text'); btn.addEventListener('click', () => { if (window.getComputedStyle(text).display === 'none') { text.style.display = 'block'; btn.textContent = 'Hide Text'; } else { text.style.display = 'none'; btn.textContent = 'Show Text'; } });
Output
When the button is clicked, the paragraph text appears or disappears and the button label changes accordingly.
Common Pitfalls
One common mistake is checking element.style.display without considering styles set in CSS. If the display is not set inline, element.style.display may be an empty string.
Also, using visibility: hidden hides the element but keeps its space, which is different from display: none.
javascript
/* Wrong way: This may fail if display is set in CSS */ if (element.style.display === 'none') { element.style.display = 'block'; } /* Right way: Use getComputedStyle to check actual display */ const style = window.getComputedStyle(element); if (style.display === 'none') { element.style.display = 'block'; }
Quick Reference
| Action | Code Example | Effect |
|---|---|---|
| Hide element | element.style.display = 'none'; | Element disappears and takes no space |
| Show element | element.style.display = 'block'; | Element appears as block |
| Toggle visibility | if (window.getComputedStyle(element).display === 'none') { element.style.display = 'block'; } else { element.style.display = 'none'; } | Switches element between hidden and shown |
| Check actual display | window.getComputedStyle(element).display | Gets current display even if set in CSS |
Key Takeaways
Use style.display = 'none' to hide and style.display = 'block' (or other) to show elements.
Check computed styles with getComputedStyle to avoid errors when display is set in CSS.
visibility: hidden hides element but keeps space; display: none removes it completely.
Toggle visibility by switching between 'none' and a visible display value.
Always test your code in the browser to see the effect immediately.