jQuery Method How to - Use appendTo() method to Append element to other from other element's click action








Question

We would like to know how to use appendTo() method to Append element to other from other element's click action.

Answer


<!DOCTYPE html>
<html>
<head>
<script type='text/javascript'
  src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<script type='text/javascript'>
$(function(){<!--from  w ww.j  a v a 2  s.c  o  m-->
    $('#main_menu li').click(function() {
        $(this).appendTo('.main_content ul')
    });
});
</script>
</head>
<body>
  <ul id="main_menu">
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
  <div class="main_content">
    main content
    <ul></ul>
  </div>
</body>
</html>

The code above is rendered as follows: