删除DOM元素

时间:2013-08-27 15:18:55

标签: javascript jquery html dom

我需要的是在jQuery或javascript的帮助下删除DOM元素。

$(document).ready(function(){
  $("#hide").click(function(){
    $("p").hide();
  });
  $("#show").click(function(){
    $("p").show();
  });
});

我尝试了hide()show(),这只会改变CSS以显示该元素。但是,我需要的是从DOM中禁用该特定元素,并在单击show时再次获取该元素。

2 个答案:

答案 0 :(得分:4)

您可以改用detach()方法。

detach()

  

.detach()方法与.remove()相同,除了.detach()保留与删除的元素关联的所有jQuery数据。当删除的元素稍后要重新插入DOM时,此方法很有用。

答案 1 :(得分:0)

<p> Hide and show this element <p>    
<button id="button">Hide/Show</button>
<script>

    var p; //sets a variable p
    $( "#button" ).click(function() {
      if ( p ) { //checks if p is empty
        p.appendTo( "body" ); //if p is not empty, appends it to the body
        p = null; //sets p to NULL
      } else {
        p = $( "p" ).detach(); //stored the detached element to p
      }
    });
    </script>

这是我正在寻找的解决方案。在@Brad M和jQuery Documentation的帮助下,我解决了它。