jQuery Before


The jQuery Before method insert content, specified by the parameter, before EACH element in the set of matched elements.

jQuery Remove


The jQuery remove method, removes the set of matched elements from the DOM.

jQuery Empty


The jQuery Empty method remove all child nodes of the set of matched elements from the DOM.

The example below shows the usage of the three methods.


<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<script type="text/javascript">
var i = 0;
jQuery(document).ready(function(e) {
  $('#bt1').click(function(e) {
    i++;
    $('#container').append('<input type="button" value="'+i+'" />');
  });
  $('#bt2').click(function(e) {
    i++;
    $('#container').prepend('<input type="button" value="'+i+'" />');
 });
$('#bt3').click(function(e) {
   i++;
  $('#container input:nth-child(2)').before('<input type="button" value="'+i+'" />');
  });
$('#bt4').click(function(e) {
  $('#container input:first-child').remove();
});
$('#bt5').click(function(e) {
   $('#container').empty();
});
});
</script>
<title>Example 03</title>
</head>

<body>
    <input id='bt1' type='button' value='add node first'/>
    <input id='bt2' type='button' value='add node last'/>
    <input id='bt3' type='button' value='add node before second node'/>
    <input id='bt4' type='button' value='delete first'/>
    <input id='bt5' type='button' value='clear all'/>
    <div id="container"></div>
</body>
</html>



We already cover the append and prepend methods in the previous post and are easy to understand. For before method, we need to define the 2nd input button and insert new input button before it. So that, we use selector $(‘#container input:nth-child(2)’). Every input will be added inside div container, so that selector always define the 2nd input button (of div container). The method before will add new input button at right position. In this example, we use click event handler. The click event handler will handle click event when user click on (example bt1, b2, bt3).
You may like to try this example here.