Which is one more expensive to call?
- showing-hiding dom node or
- creating-deleting dom node
Assume there is only 1 dom or a few (less than 5) nodes that we need to manipulate and the application runs on desktop.
For a small number, does it even matter at all?
How about for mobile applications?
The difference between the two will be infinitesimally small for only a few elements — it could absolutely be considered negligible.
That being said, showing and hiding the element via CSS will be faster unless you use jQuery’s
.show()and.hide(). jQuery’s.hide()is much slower than any other method of hiding an element. If you’d like to know why, read the “Why is.hide()slower?” section at the bottom of my answer.Anyway, you should make your decision based on which method suits your needs best. If you don’t ever need the element again, you may as well delete it. If you just wan’t to hide it for a little while or under certain conditions, show/hide it.
But if you want to test it yourself, here ya go 🙂
Why is
.hide()slower?jQuery’s
.hide()is basically the same as using.css('display','none')except that it caches the previous value of thedisplaystyle, so that when you call.show(), your element will be correctly reverted to look the exact same as it did. If it haddisplay:inline, it’ll have it when it gets re-shown. If it haddisplay:block, it’ll havedisplay:block. This can be pretty useful.Here’s an example:
lets say we have a div with id=”myDiv” and it is styled in an external file with
display:inline. We want to hide it.With the
.cssway, we’d do this:and then later on sometime, one of your fellow developers wants to show it again under certain conditions. He’ll have no idea what the
displayproperty should be, since the css is in an external file somewhere. Most developers default todisplay:block, like this:However in this case, we’d get a totally different style, since it was originally
inline. A clever developer will have no problem figuring out what went wrong, but not all developers are clever 🙂With
.show()and.hide(), this becomes a non issue. We don’t care what style it used to have. We just want it to be back where it was, and that’s exactly what it’ll do.