Chaining jQuery

jQuery methods return nodes, so we can easily chain these steps together.

Stepwise:

$(document).ready(function() {
    var numberofphones = 1;
    $('#addphone').click(function() {
      numberofphones++;
      newid = 'phone' + numberofphones;
      var phonediv = $('#phone1');
      var newphonediv = phonediv.clone();
      newphonediv.attr('id',newid);
      newphonediv.insertBefore('#addphone');
  });
 });

Chained:

$(document).ready(function() {
    var numberofphones = 1;
    $('#addphone').click(function() {
      numberofphones++;
      newid = 'phone' + numberofphones;
      $('#phone1').clone().attr('id',newid).insertBefore('#addphone');
  });
 });

Copyright © David Heitmeyer