.remove()

Remove the set of matched elements from the DOM.

Similar to .empty(), the .remove() method takes elements out of the DOM. Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use .detach() instead.

Consider the following HTML:

<div class="container">
  <div class="hello">Hello</div>
  <div class="goodbye">Goodbye</div>
</div>

We can target any element for removal:

$( ".hello" ).remove();

This will result in a DOM structure with the <div> element deleted:

<div class="container">
  <div class="goodbye">Goodbye</div>
</div>

If we had any number of nested elements inside <div class="hello">, they would be removed, too. Other jQuery constructs such as data or event handlers are erased as well.

We can also include a selector as an optional parameter. For example, we could rewrite the previous DOM removal code as follows:

$( "div" ).remove( ".hello" );

This would result in the same DOM structure:

<div class="container">
  <div class="goodbye">Goodbye</div>
</div>
version added: 1.0
selector

A selector expression that filters the set of matched elements to be removed.

Examples:

Removes all paragraphs from the DOM

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>remove demo</title>
  <style>
  p {
    background: yellow;
    margin: 6px 0;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<p>Hello</p>
how are
<p>you?</p>
<button>Call remove() on paragraphs</button>
 
<script>
$( "button" ).click(function() {
  $( "p" ).remove();
});
</script>
 
</body>
</html>

Removes all paragraphs that contain "Hello" from the DOM. Analogous to doing $("p").filter(":contains('Hello')").remove().

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>remove demo</title>
  <style>
  p {
    background: yellow;
    margin: 6px 0;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
<p class="hello">Hello</p>
how are
<p>you?</p>
<button>Call remove( ":contains('Hello')" ) on paragraphs</button>
 
<script>
$( "button" ).click(function() {
  $( "p" ).remove( ":contains('Hello')" );
});
</script>
 
</body>
</html>
doc_jQuery
2016-03-27 13:48:57
Comments
Leave a Comment

Please login to continue.