jQuery is a popular JavaScript library that simplifies HTML document traversal, manipulation, event handling, and
animation. One common use of jQuery is hiding and showing elements quickly and easily. In this tutorial, we will
learn how to hide a div element by its ID using jQuery.
Prerequisites
In order to follow along with this tutorial, you need to have the following:
- Basic knowledge of HTML, CSS, and JavaScript
- jQuery library included in your project
If you haven’t included the jQuery library in your project yet, you can do so by adding the following script
tag in the head section of your HTML file:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Step 1: Create the HTML Structure
First, let’s create a simple HTML structure with a div element that we want to hide using jQuery. Give the div
element an ID attribute, which we will use to target it in jQuery.
<meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Hide Div Example</title> <div id="myDiv"> <p>Hello, World!</p> </div> <button id="hideButton">Hide Div</button>
Step 2: Hide the Div Using jQuery
Now that we have our HTML structure in place, let’s use jQuery to hide the div element when the “Hide Div”
button is clicked. To do this, we will use the $(“#elementID”).hide() function, which selects
the element with the specified ID and hides it.
First, let’s add a script tag to include our custom JavaScript code. Add the following script tag just before
the closing </body> tag:
<script> // Your JavaScript code goes here </script>
Inside the script tag, let’s write our jQuery code to hide the div when the button is clicked. Add the
following code inside the script tag:
$(document).ready(function () { $("#hideButton").click(function () { $("#myDiv").hide(); }); });
The $(document).ready() function ensures that our code will only run once the page has
finished loading. The $(“#hideButton”).click() function binds a click event to the button with
the ID “hideButton”. When the button is clicked, the function inside the click event is executed, which hides
the div with the ID “myDiv” by calling the $(“#myDiv”).hide() function.
Conclusion
In this tutorial, we learned how to hide a div element by its ID using jQuery. This can be a useful technique
for showing and hiding content dynamically on your web pages. You can now apply this knowledge to your own
projects and explore other jQuery functions to enhance the interactivity of your website.