views:

432

answers:

4
<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

A: 
Ed Woodcock
A: 

You can do something like this:

$('a').click(function(){
   $('li').each(function(){
      $(this).clone().appendTo('your selector where to put the copy');
   })
})
Reigel
+8  A: 

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.

patrick dw
This will break quite badly if there's another UL on the page though. It's almost always a bad idea to use jQuery without class or id selectors!
Ed Woodcock
@Ed Woodcock - Read the rest of my answer... I was working with what I was given, then suggested specifying the 'a' and 'ul' with a class or id.
patrick dw
@patrick Yes, I didn't disagree with your answer, I was just stating that it was bad to not use selectors: the problem with posting semi-correct code like your answer is that the inexperienced or confused will use the code without reading the rest of the answer, and that's a bad thing!
Ed Woodcock
@Ed Woodcock - Point taken, though I prefer to give an answer that is specific to the question accompanied by a warning if warranted. Perhaps it would be better if I were to add an alternate answer in case the context of the page didn't allow for the specific answer to function properly. I'll update my answer with such.
patrick dw
@patrick fair enough, it's just that you often find people on here latch onto a bad solution even when told of the pitfalls so it can be good to point out better ways of doing things straight off! :)
Ed Woodcock
+1  A: 
var ul = $('ul');

$('a').click(function(){
    ul.children().clone(true).appendTo(ul);
});
J-P