How to Hide an HTML Element with jQuery


In this article, we show how to hide an HTML element with jQuery.

So hiding elements can be very useful for a web page.

Say if you have a website that allows user comments and only one reply comment box can be open at a time. When a user opens one comment box, you want to close, collapse, or hide all remaining comment boxes. This is the potential value of the hide() function in jQuery. It can collapse all elements needed.

So jQuery has a built-in hide() function, which will hide an element or elements based on the code.

In this example, we will create a button that has an id of savebutton. When this button is clicked, it will disappear. You can demo this below.

Below is the HTML code for this button.

So now we will go to the jQuery code that allows this button to disappear once clicked. This is shown below.

So now we go over this code.

So at the top of the code, you must always import your jQuery code, so that jQuery can work. In the above example, we use the google CDN to allow jQuery to work on our page.

After this, we have our jQuery code.

The first thing you must always put in jQuery code is $(function() { });

This line says that whenever the page has fully loaded, then run this code. Without this, the jQuery code will not work.

Since we gave our button an id of 'savebutton', then we have, $('#savebutton'), to identify this button.

# identifies ids, while . identifies classes.

The rule of thumb is that ids are given to represent individual elements, while classes are used to represent groups of elements.

What we want to do in this code is that when the button is clicked, we hide it. So we use the jQuery click event handler to listen for clicks.

Once a click occurs on this element, then we hide it using the jQuery hide() function.

So if you demo the button above, you will see that it is hidden once clicked.

And this is how you can hide an HTML element with jQuery.

Related Resources

How to Create a Comment System in Which Only One Reply Comment Box Can Be Open At Once with jQuery

How to Upload a File with the Click of an Image with jQuery

HTML Comment Box is loading comments...