Difference between jQuery .hide() and .css("display", "none")
Solution 1:
jQuery('#id').css("display","block")
The display
property can have many possible values, among which are block
, inline
, inline-block
, and many more.
The .show()
method doesn't set it necessarily to block
, but rather resets it to what you defined it (if at all).
In the jQuery source code, you can see how they're setting the display
property to "" (an empty string) to check what it was before any jQuery manipulation: little link.
On the other hand, hiding is done via display: none;
, so you can consider .hide()
and .css("display", "none")
equivalent to some point.
It's recommended to use .show()
and .hide()
anyway to avoid any gotcha's (plus, they're shorter).
Solution 2:
Difference between show() and css({'display':'block'})
Assuming you have this at the beginning:
<span id="thisElement" style="display: none;">Foo</span>
when you call:
$('#thisElement').show();
you will get:
<span id="thisElement" style="">Foo</span>
while:
$('#thisElement').css({'display':'block'});
does:
<span id="thisElement" style="display: block;">Foo</span>
so, yes there's a difference.
Difference between hide() and css({'display':'none'})
same as above but change these into hide() and display':'none'......
Another difference
When .hide()
is called the value of the display property is saved in jQuery's data cache, so when .show()
is called, the initial display value is restored!
Solution 3:
Yes there is a difference in the performance of both:
jQuery('#id').show()
is slower than jQuery('#id').css("display","block")
as in former case extra work is to be done for retrieving the initial state from the jquery cache as display is not a binary attribute it can be inline
,block
,none
,table
, etc.
similar is the case with hide()
method.
See: http://jsperf.com/show-vs-addclass