main.html:
<body>
<div class="lists">
<ul id="list1">
<li><button id="toList2">></button> Item 1.1</li>
<li><button id="toList2">></button> Item 1.2</li>
<li><button id="toList2">></button> Item 1.3</li>
<li><button id="toList2">></button> Item 1.4</li>
</ul>
<ul id="list2">
<li><button id="toList1"><</button> Item 2.1</li>
<li><button id="toList1"><</button> Item 2.2</li>
</ul>
</div>
<button id="all-left"><<</button>
<button id="all-right">>></button>
<script src="/script.js"></script>
</body>
script.js:
let allLeft = document.querySelector('#all-left');
let allRight = document.querySelector('#all-right');
let list1 = document.querySelector('#list1');
let list2 = document.querySelector('#list2');
let list1Elem = document.querySelectorAll('.i1');
let list2Elem = document.querySelectorAll('.i2');
list1.addEventListener('click',(e)=>{
if(e.target != this) {
list2.appendChild(e.target.parentElement.cloneNode(true));
e.target.parentElement.remove();
}
})
list2.addEventListener('click',(e)=>{
if(e.target != this) {
list1.appendChild(e.target.parentElement.cloneNode(true));
e.target.parentElement.remove();
}
})
//Problem Section
All's fine when I add a list elements to another list individually from list 1 to 2 or vice-versa. But when I click these(<<, >>) buttons to move everything in a list to another list, it works at first go, but when I click any alternate button again then the elements that are added already in the list while loading DOM, they just keep moving from one to other list. The list which I updated after loading DOM those updated elements are not adding.
I think event delegation will be used here but how?? I need to iterate over the elements in the list with updated ones but getting only which are defined in html document?
document.body.addEventListener('click',(e)=>{
if(e.target.id=='all-right') {
list1Elem.forEach((e)=>{
list2.appendChild(e.cloneNode(true));
e.remove();
})
}
if(e.target.id=='all-left') {
list2Elem.forEach((e)=>{
list1.appendChild(e.cloneNode(true));
e.remove();
})
}
})