Search code examples
jquerylistcloneappendpopulate

Populating a list dynamically (jQuery)


<ul>
  <li>item x</li>
  <li>item y</li>
  <li>item z</li>
</ul>
<a href="#">Populate</a>

I want to duplicate (copy and append) all <li>s when clicked on the 'populate' link. How do I do it?

Thanks


Solution

  • Quick and concise version.

    $('a').click(function() {
        $('ul').children().clone().appendTo('ul');
    })
    

    Of course, you may want to define your 'a' and 'ul' with a class or id in order to be more specific.

    EDIT:

    To expand on the disclaimer given above, this will be a somewhat fragile solution as it will affect all 'a' and 'ul' elements. This may likely not be what you desire.

    Better form is to give your html elements classes or ids, and then attach events to those.

    Example:

    $('#myPopulateAnchorElement').click(function() {
     $('#myExpandableUL').children().clone().appendTo('#myExpandableUL');
    });
    
    <ul id='myExpandableUL'>
      <li>item x</li>
      <li>item y</li>
      <li>item z</li>
    </ul>
    <a href="#" id='myPopulateAnchorElement'>Populate</a>
    

    With thanks to Ed Woodcock for suggesting the inclusion of a preemptive solution.