Trusted answers to developer questions

How to hide an element in JavaScript

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

Javascript uses the style.display property to hide or show HTML elements; it does this by accessing the individual objects in the DOM object and setting the property.

The DOM object establishes parent-child relationships and adjacent sibling relationships among the various elements in the HTML file.


Code

The following code shows a sample HTML file and its corresponding DOM object:

<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
</body>
</html>
DOM object corresponding to the above HTML file
DOM object corresponding to the above HTML file

Example

We can use Javascript to access and change the properties of these DOM elements. The following Javascript code, written within HTML, accesses a paragraph in the HTML and sets its style.display property to none to hide it.

Another property that hides elements in Javascript is style.visibility. However, the main difference between it and style.display is that, by setting the style.visibility property to hidden, the space of the element remains allocated in the output, only its visibility changes.

On the other hand, style.display also removes the space allocation of that element from the output screen.

RELATED TAGS

javascript
element
hide
dom
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?