We can use jQuery display none to easily hide an HTML element. We can do this by using the jQuery css() method to target the display property of an element and change it to none.
$("#div1").css("display", "none");
We can also get the same result by using the jQuery hide() method, which requires a little less code.
$("#div1").hide();
Hiding a Div using jQuery is very easy using the css() method and targeting the display property.
Let’s say we have the following HTML:
This is a Div that we can hide with jQuery
This is a Div that we will NOT can hide
We want to hide the div with id #div1, so we will use the jQuery css() method and set the display property to none. If we wanted to hide the div when the web page initially loads the JavaScript file, it would look like this:
$(document).ready(function() {
$("#div1").css("display","none");
});
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery("#div1").css("display","none");
The jQuery css() method is very useful for changing the styling of a HTML element dynamically – for example, changing the background color of a div.
Another way you can hide a div using jQuery is to use the jQuery hide() method:
$("#div1").hide();
Note that we can also hide a Div in just plain JavaScript using the display property.
Using jQuery Display None With a Click
We can use jQuery to hide a div very easily by combining the css() method with a click event.
Let’s say that we have the following HTML where we want to give the user the ability to hide “#div1”:
Div 1
Div 2
Hide Div 1
We can utilize both the jQuery click() method and jQuery css() method to set the display property of “Div 1” to none, which will hide the div.
Below is the jQuery code which will allow the user to be able to hide “Div 1”:
$("#click-me").click(function(){
$("#div1").css("display","none"); // Results in the element #div1 being hidden
});
The final code and output for this example of using jQuery display none to hide a div with a click is below:
Code Output:
Full Code:
Div 1
Div 2
Hide Div 1
Hopefully this article has been useful for you to understand how to use jQuery display none to hide an element.