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