Home > Back-end >  How to copy contents of list items from one list to another
How to copy contents of list items from one list to another

Time:11-12

I need to copy the contents of each <li> in a list to a corresponding <li> in another list. So the first item from #list1 would go into the first item of #list2. The third item of #list1 would go into the third item of #list2.

Here is my html:

<ul id="list1">
    <li>List Item 1</li>
    <li>List Item 2</li>
    <li>List Item 3</li>
    <li>List Item 4</li>    
    <li>List Item 5</li>
    <li>List Item 6</li>
    <li>List Item 7</li>        
</ul>


<ul id="list2">
    <li >COPY GOES HERE</li>
    <li >COPY GOES HERE</li>
    <li >COPY GOES HERE</li>
    <li >COPY GOES HERE</li>
    <li >COPY GOES HERE</li>
    <li >COPY GOES HERE</li>            
</ul>

I tried the following, but it copies the whole <li> elements, and I only want to copy the text inside each <li>:

$(newList).html($(oldlist).html());

Then I tried this, but couldn't get it to work:

var headings = '';
    
$("#list1 li").each(function(idx, li) {
        headings = $(li).html();
});
    
  
$("#list2 li").each(function(idx, li) {
       var items = $(li).html();
    
       $( items ).html( headings );
       
});

Any ideas? Thank you!

CodePudding user response:

Please try to do it with below code

const list1 = document.querySelectorAll('#list1 li'),
      list2 = document.querySelectorAll('.list2');

list2.forEach((list) => {
  const newList = list.querySelectorAll('li');
  list1.forEach((li, index) => newList[index] ? newList[index].textContent = li.textContent : '');  
})
<ul id="list1">
    <li>List Item 1</li>
    <li>List Item 2</li>
    <li>List Item 3</li>
    <li>List Item 4</li>    
    <li>List Item 5</li>
    <li>List Item 6</li>
    <li>List Item 7</li>        
</ul>


<ul >
    <li >COPY GOES HERE</li>
    <li >COPY GOES HERE</li>
    <li >COPY GOES HERE</li>
    <li >COPY GOES HERE</li>
    <li >COPY GOES HERE</li>
    <li >COPY GOES HERE</li>            
</ul>

<ul >
    <li >COPY GOES HERE</li>
    <li >COPY GOES HERE</li>
    <li >COPY GOES HERE</li>
    <li >COPY GOES HERE</li>
    <li >COPY GOES HERE</li>
    <li >COPY GOES HERE</li>
    <li >COPY GOES HERE</li>   
</ul>

  • Related