How to destroy a DOM element with jQuery?

前端 未结 4 1928
攒了一身酷
攒了一身酷 2020-12-01 08:51

Suppose the jQuery object is $target.

相关标签:
4条回答
  • 2020-12-01 09:11

    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

    0 讨论(0)
  • 2020-12-01 09:33

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

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

    0 讨论(0)
  • 2020-12-01 09:34

    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();

    0 讨论(0)
  • 2020-12-01 09:35

    You are looking for the .remove() function.

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

    0 讨论(0)
提交回复
热议问题