jQuery Remove


To delete existing HTML elements or contents from the text, jQuery provides a number of methods such as empty(), remove(), unwrap() and so on.


The empty() method


The jQuery empty() method clears the DOM of all child elements, descendant elements, and text content within the selected elements.

On clicking the button, the following example will delete all content from elements with the class .container.



$(document).ready(function(){
  // Empty
  // container element
  $("button").click(function(){
    $(".container").empty();
  });
});

Live Demo!


The remove() method


The remove() method of the jQuery library removes the selected elements from the DOM, as well as all inside it. All bound events and jQuery data associated with the elements are deleted, in addition to the elements themselves.

On button press, the following example will delete all <p> elements with the class .hint from the DOM. Within these paragraphs, nested elements will be omitted as well.



$(document).ready(function(){
  // Removes paragraphs
  // with class "hint" from DOM
  $("button").click(function(){
    $("p.hint").remove();
  });
});

Live Demo!


A selector can be passed as an optional parameter to the jQuery remove() process, allowing you to filter the elements to be removed. For example, the jQuery DOM removal code in the previous example could be rewritten as follows:



$(document).ready(function(){
  // Removes paragraphs with class "hint" from DOM
  $("button").click(function(){
    $("p").remove(".hint");
  });
});

Live Demo!


The unwrap() method


The jQuery unwrap() method clears the DOM of the selected elements' parent elements. In most cases, this is the opposite of the wrap() form.

On button press, the parent element of <p> elements is removed in the following example.



$(document).ready(function(){
  // Removes the paragraph's parent element
  $("button").click(function(){
    $("p").unwrap();
  });
});

Live Demo!


The removeAtrr() method


The removeAttr() method of the jQuery library removes an object attribute.

On button click, the href attribute is removed from the <a> elements in the example below:



$(document).ready(function(){
  // Removes the hyperlink's href attribute
  $("button").click(function(){
    $("a").removeAttr("href");
  });
});

Live Demo!