Difference between remove and empty methods in javascript

Most of the times, these methods are confused with each other or are thought of as performing the same functionality. But,remove() removes the selected element and all its child elements whereas empty() removes only the child elements from the selected element. Moreover, we can also filter the element to be removed in a specific class by giving a parameter of that class to the remove() function. We will see the difference by example:

$("#divTwo").remove(); //remove the selected element and its child elements.
$("#divDetail").empty(); //remove the child elements of the selected element and make it empty 
$("p").remove(".country"); //remove all <p> elements with class="country"

From the name and example, it is easy to understand that empty will remove all child elements and make the main element empty. It won’t actually remove the main element but make it empty by removing all its child elements. Now, we can easily differentiate between the two.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Create a free website or blog at WordPress.com.

Up ↑

Create your website at WordPress.com
Get started
%d bloggers like this: