To hide an element by id, you can use JavaScript in two commonly used methods: the display property or the visibility property, which are easily approached currently. I will introduce both ways to you and show the difference between the two steps below.
Hide an element by id using JavaScript
Using the display property
The display property is used to specify how the element should be displayed. This property will display the elements as block elements, inline elements, not be displayed, etc. To hide an element, we have to set the style of the display property to ‘none
‘. The entire element will be hidden and no longer take up space on the document layout.
Syntax:
element.style.display= "none"
By set style.display= “none” the element will not be displayed
Example:
Let’s try to hide the paragraph whose id is “myParagraph”.
<!DOCTYPE html> <html> <body> <p id="myParagraph">This paragraph will be hidden</p> <button onclick="hide()"> Hide paragraph above</button> <script> function hide(){ // Select elements of the specific id var element= document.getElementById("myParagraph"); // Hide selected element element.style.display= "none"; } </script> </body> </html>
Output:
The paragraph above has been hidden, and the button below has been pushed up to replace it.
Using the visibility property
The visibility property determines whether a particular element is displayed on the web page. This way, we have to use the value ‘hidden
‘ to hide the HTML element. The element will be invisible, and its position and size will be kept the same as the original.
Syntax:
element.style.visibility= "hidden"
By set style.visibility= “hidden” the element will be invisible
Example:
<!DOCTYPE html> <html> <body> <p id="myParagraph">This paragraph will be hidden</p> <button onclick="hide()"> Hide paragraph above</button> <script> function hide(){ // Select elements of the specific id var element= document.getElementById("myParagraph"); // Hide selected element element.style.visibility= "hidden"; } </script> </body> </html>
Output:
By this course of action, the hidden paragraph becomes invisible, which means that its position will be preserved without being replaced by any element. This is the primary difference between using the visibility property and using the display property.
Summary
Via the examples and explanations above, I have briefly introduced two approaches to hiding an element by id using JavaScript. And I have also pointed out the fundamental difference between the two ways. In general, both methods are prevalent and accessible, and you can select the most suitable one depending on the results you want.

Hi, I’m Mary Ralston. I have experience programming in HTML, javascript, C++,… and I want to share with you my experience. So if you want to know more about the above languages read my articles