Currently, I am working on a task that involves moving list items between two separate lists and then returning them back upon a click event trigger.
Below is a snippet of the basic HTML structure:
Unchosen: <br>
<ul id="unchosen"></ul>
Chosen: <br>
<ul id="chosen"></ul>
<script src="app.js"></script>
And this is the content of app.js
:
const unchosenList = document.querySelector('#unchosen');
const chosenList = document.querySelector('#chosen');
let data = [
{
id: 1,
name: 'John Doe'
},
{
id: 2,
name: 'Jane Doe'
}
];
data.forEach(e => unchosenList.insertAdjacentHTML('afterbegin', `<li id='person'>${e.name}</li>`));
let person = document.querySelectorAll('#person');
function moveList() {
person.forEach(e => {
e.addEventListener('click', function() {
this.parentNode.removeChild(this);
chosenList.insertAdjacentHTML('afterbegin', `<li id='chosen-person'>${this.textContent}</li>`);
});
});
}
if(person) {
moveList();
}
let chosenPerson = document.querySelectorAll('#chosen-person');
function returnList() {
chosenPerson.forEach(e => {
e.addEventListener('click', function() {
this.parentNode.removeChild(this);
unchosenList.insertAdjacentHTML('afterbegin', `<li id='person'>${this.textContent}</li>`);
});
});
}
if(chosenPerson) {
returnList();
}
The issue arises with the returnList
function not working as intended due to chosenPerson
being undefined. Moreover, there are concerns about how the functionality will impact the existing person
array. Any insights or suggestions would be greatly appreciated!