Cover Image for jQuery empty() method
85 views

jQuery empty() method

The jQuery empty() method is used to remove all child elements and text content from the selected elements. It effectively clears the content inside the matched elements, making them empty.

The syntax for using the empty() method is as follows:

$(selector).empty();
  • selector: It is a string that specifies the elements to be selected.

Here’s an example of how you can use the empty() method:

HTML:

<div id="myDiv">
  <p>This is some text inside the div.</p>
  <span>This is a span element.</span>
</div>

JavaScript:

// Empty the content inside the div element
$('#myDiv').empty();

After executing the above JavaScript code, all the child elements and text content inside the div element with the ID “myDiv” will be removed:

Resulting HTML:

<div id="myDiv"></div>

The empty() method is commonly used when you want to clear the content of an element, such as when you need to reset a container or remove dynamically generated content.

Keep in mind that the empty() method only removes the content of the selected elements and does not remove the elements themselves. If you want to remove the elements as well, you can use the remove() method instead.

// Remove the entire div element and its content from the DOM
$('#myDiv').remove();

In summary, the empty() method is used to quickly remove the content inside elements, while the remove() method is used to completely remove the elements along with their content from the DOM.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS