When working with web pages, you may come across situations where you want to hide an element from view, such as a loading icon or a tooltip. One way to accomplish this is by using the display property in CSS, setting it to none. In this blog post, we’ll discuss how to achieve this using jQuery.
Using the .css() method
jQuery provides a versatile method called .css() that allows you to get or set the CSS properties of an element. To hide an element using the .css() method, you simply need to pass two parameters: the name of the CSS property you want to set (in this case, ‘display’) and the value you want to set it to (in this case, ‘none’).
Let’s say we have a div element with the ID “myElement” that we want to hide:
<div id="myElement"> This content will be hidden. </div>
To hide this element using jQuery, we can use the following code:
The element with the ID “myElement” will now be hidden from view.
Using the .hide() method
jQuery also provides a more convenient method for hiding elements called .hide(). This method achieves the same result as the previous example but with less code. The .hide() method sets the display property of the selected element to ‘none’ without needing to specify the property name and value.
Continuing with the previous example, we can hide the “myElement” div using the .hide() method as follows:$('#myElement').hide();
The “myElement” div will be hidden just as before, but with a more concise syntax.
In this blog post, we discussed two methods to set the display property of an element to ‘none’ in jQuery: the .css() method and the .hide() method. Both methods are useful for hiding elements on your web page, but the .hide() method is more concise and specific to this use case, making it the preferred choice in most situations.