Comparing jQuery empty, hide, remove and detach functions

jQuery is the best javascript library of all time. It reduces the size of code to do a task with javascript. jQuery has lot of in-built functions. I’m comparing four functions such as .empty(), .hide(), .remove() and .detach() in this article to make you understand which function should be used in which place.

Confusion

The similarity in these four functions is that they remove the specified elements from certain place. But there is distinct difference between these four functions.

Each function has its own purpose which I’m going to explain to you with examples.

.empty()

empty function basically deletes all the content inside of the selector. For instance, say you have a paragraph in your page. If you want to empty the text inside of the paragraph tag whenever a button is clicked, you can use jquery empty function to do that.

The parent tag will remain as it is. In this case paragraph tag stays as it is but the text will be deleted.

.hide()

hide function doesn’t actually remove an element from DOM. But it hides the element from the display. Whenever the hide function executed for a selector it will add “display:none;” style parameter to that element.

So you can show that element whenever you want using .show() function (There are other functions also to do this).

Conclusioin

To say the differences in one sentence, empty function removes the child elements, hide function hides the element from display, remove function completely deletes from DOM and detach function keeps the element after removal.

Note: all these removal are done in run time only. If you refresh the page all the deleted elements will come back to the place. If you want the change to be affected permanently, you have to store the changes somewhere.