append vs appendTo

append() and appendTo() methods do the same task. Both methods add the content to the end of existing content. However I prefer appendTo(), because it might make the code more readable.

The main difference is way to write the code. With append() method target element come first and source element come in last, but in appendTo() method source element come first and target come last of the code.

append()

$('#container').append('<p>Hi, I am added by append.</p>');

appendTo()

$('<p>Hi, I am added by appendTo.</p>').appendTo($('#container'));
CODE
<!DOCTYPE html>
<html>
<head>
  <title>jQuery With Example</title>
  <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(function () {
      $('.btnAppend').click(function () {
        $('#container').append('<p>Hi, I am added by append.</p>');
      });

      $('.btnAppendTo').click(function () {
        $('<p>Hi, I am added by appendTo.</p>').appendTo($('#container'));
      });
    });
  </script>
</head>
<body>
  <button class="btnAppend">append</button>
  <button class="btnAppendTo">appendTo</button>
  <div id="container">Container</div>
</body>
</html>
DISPLAY
Container

No comments :

Please Give Your Feedback