Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to copy contents of list items from one list to another

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 class="item yes">COPY GOES HERE</li>
    <li class="item yes">COPY GOES HERE</li>
    <li class="item yes">COPY GOES HERE</li>
    <li class="item">COPY GOES HERE</li>
    <li class="item">COPY GOES HERE</li>
    <li class="item">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>:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$(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!

>Solution :

Please try to do it with below code

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

list1.forEach((li, index) => list2[index] ? list2[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 id="list2">
    <li class="item yes">COPY GOES HERE</li>
    <li class="item yes">COPY GOES HERE</li>
    <li class="item yes">COPY GOES HERE</li>
    <li class="item">COPY GOES HERE</li>
    <li class="item">COPY GOES HERE</li>
    <li class="item">COPY GOES HERE</li>            
</ul>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading