1
1

More than 1 year has passed since last update.

【jQuery】要素の追加、削除の方法(append,prepend,remove,empty..)

Posted at

要素の追加、削除方法

1.追加
・append
・prepend
・after
・before

2.削除
・remove //要素自身を削除
・empty   //子要素を削除
・html("")  //要素の内容を削除

追加

demo:https://jsfiddle.net/boababy/w7d9j5vk/12/

<ul>
  <li>最初のli</li>
</ul>

<div> 元div</div>

<script>
  $(function(){

  //内部追加
    var li=$("<li>後付けのli append</li>")
    var li2=$("<li>後付けのli prepend</li>")

    $("ul").append(li)
    $("ul").prepend(li2)

  //外部追加
    var div1=$("<div>後付けのdiv before</div>")
    var div2=$("<div>後付けのdiv after</div>")

    $("div").before(div1)
    $("div:eq(1)").after(div2)  

});

</script>

削除

demo:https://jsfiddle.net/boababy/xwom24j8/9/


<div class="remove">
remove
</div>
<button id="remove-bt" type="button">
remove element
</button>

<div class="empty">
<p>empty</p>
<p>empty</p>
</div>
<button id="empty-bt" type="button">
empty element
</button>

<div class="html">
<p>html</p>
<p>html</p>
</div>
<button id="html-bt" type="button">
use html empty element
</button>

<script>
$(function(){

   $("#remove-bt").click(function(){
      $(".remove").remove()
   })


   $("#empty-bt").click(function(){
      $(".empty").empty()
   })

   $("#html-bt").click(function(){
      $(".html").html("")
   })


});
</script>


1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1