casiokid
casiokid

Reputation: 119

Inserting elements and values of list into another list

I can't figure out the best way to extract the contents of a list item and insert into another list. So I want <a> and <img> elements with their values from list one to be inserted into list two.

Here's my code so far:

var listInfo = $("ul#list-one li").map(function(){
  return $(this).html();
});

??
<ul id="list-one">
  <li>
    <a href="example1.com"><img src="image1.jpg"/></a>
  </li>
  <li>
    <a href="example2.com"><img src="image2.jpg"/></a>
  </li>
  <li>
    <a href="example3.com"><img src="image3.jpg"/></a>
  </li>
</ul>

<ul id="list-two">
  <li>
    
  </li>
  <li>
 
  </li>
  <li>
  
  </li>
</ul>

Upvotes: 0

Views: 48

Answers (1)

j08691
j08691

Reputation: 207900

$('#list-two li').each(function(i){
    $(this).append($('#list-one li:eq('+i+')').contents())
})

jsFiddle example

Results in the HTML:

<ul id="list-one">
    <li></li>
    <li></li>
    <li></li>
</ul>
<ul id="list-two">
    <li><a href="example1.com"><img src="image1.jpg"></a> </li>
    <li><a href="example2.com"><img src="image2.jpg"></a> </li>
    <li><a href="example3.com"><img src="image3.jpg"></a> </li>
</ul>

Upvotes: 2

Related Questions