Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

JQuery adds elements and removes them


May 30, 2021 Article blog


Table of contents


JQuery adds elements and removes them

1. jQuery creates the element method

let div = $('<div>elm</div>');

$('elm') creates a div element with the content elm

2. Add elements

2.1. Internally add append(), prepend() method

<ul>
   <li>原有的</li>
</ul>
<script>
   $(function() {
       let li = $('<li>后加的</li>');
       $('ul').append(li);
  });
</script>

The append() method adds an element to the last face of the matching element, similar to the appendChild() in the native JS

<ul>
  <li>原有的</li>
</ul>
<script>
  $(function() {
      let li = $('<li>后加的</li>');
      $('ul').prepend(li);
  });
</script>

The prepend() method adds elements to the front of the matching element, similar to insertBefore() in native JS

When elements are added internally, a parent-child relationship is generated

2.2. External addition (before), after() method

Original
$(function() { let div = $('
Added
'); $ ('div').before(div); })

The before method adds the element before the matching element

<div>原来的</div>
<script>
   $(function() {
       let div = $('<div>添加的</div>');
       $('div').after(div);
  })
</script>

The after() method adds elements after matching elements

Externally add elements, resulting in a brotherly relationship

2. Delete the element

1.remove()

<ul>
   <li></li>
</ul>
<script>
   $(function() {
       $('ul').remove();
  })
</script>

remove() remove removes the ul element, including the child nodes

2.empty()

<ul>
   <li></li>
</ul>
<script>
   $(function() {
       $('ul').empty();
  })
</script>

empty() clears all child nodes within the ul node, but retains the ul itself node

3.html("")

The html (") method works in the same way as empty().

Recommended lessons: jquery micro-class, jquery getting started