How to destroy a DOM element with jQuery?

JqueryDom

Jquery Problem Overview


Suppose the jQuery object is $target.

Jquery Solutions


Solution 1 - Jquery

Is $target.remove(); what you're looking for?

https://api.jquery.com/remove/

Solution 2 - Jquery

If you want to completely destroy the target, you have a couple of options. First you can remove the object from the DOM as described above...

console.log($target);   // jQuery object
$target.remove();       // remove target from the DOM
console.log($target);   // $target still exists

Option 1 - Then replace target with an empty jQuery object (jQuery 1.4+)

$target = $();
console.log($target);   // empty jQuery object

Option 2 - Or delete the property entirely (will cause an error if you reference it elsewhere)

delete $target;
console.log($target);   // error: $target is not defined

More reading: info about empty jQuery object, and info about delete

Solution 3 - Jquery

You are looking for the .remove() function.

http://docs.jquery.com/Manipulation/remove

Solution 4 - Jquery

Not sure if it's just me, but using .remove() doesn't seem to work if you are selecting by an id.

Ex: $("#my-element").remove();

I had to use the element's class instead, or nothing happened.

Ex: $(".my-element").remove();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionomgView Question on Stackoverflow
Solution 1 - JqueryJourkeyView Answer on Stackoverflow
Solution 2 - JqueryLukeView Answer on Stackoverflow
Solution 3 - JqueryShardView Answer on Stackoverflow
Solution 4 - JqueryRichardView Answer on Stackoverflow