How can I replace the whole list without adding new li’s to the list?
I think I should “reboot” it somehow, but I’m not sure how. I could just do it by filling empty li’s in the HTML file, but then I’ll have a problem when there are more or less items.
let objects = [
{
"id": 1,
"name": "broom",
"places": ["kitchen", "shop", "pharmacy"]
},
{
"id": 2,
"name": "wheels",
"places": ["park", "pool", "square"]
},
{
"id": 3,
"name": "wood",
"places": ["church", "garage", "bathroom"]
}
];
const nameObject = document.getElementById('objectName');
const nextBtn = document.getElementById('objectNext');
let objectIndex = 0;
nextBtn.onclick = function () {
objectIndex === objects.length - 1 ?
objectIndex = 0 :
objectIndex ++;
nameObject.innerHTML = objects[objectIndex].name;
objects[objectIndex].places.forEach(place => {
createPlaceListItem(place);
});
};
const createPlaceListItem = place => {
const $item = document.createElement(`li`);
$item.classList.add(`objectListItem`);
$item.innerHTML = place;
document.getElementById(`placeList`).appendChild($item);
};
nameObject.innerHTML = objects[objectIndex].name;
objects[objectIndex].places.forEach(place => {
createPlaceListItem(place);
});<h4 id="objectName" class="objectName"></h4> <ul class="objectList" id="placeList"> </ul> <button class="objectNext" id="objectNext">next</button>
Thanks!
Advertisement
Answer
While using innerHTML to clean the list is effective, using a proper removeChild is not only arguably more idiomatic but also faster (although the performance will not matter for such small lists). It can be just:
while (list.firstChild) list.removeChild(list.firstChild);
Here is your code with that line:
let objects = [{
"id": 1,
"name": "broom",
"places": ["kitchen", "shop", "pharmacy"]
},
{
"id": 2,
"name": "wheels",
"places": ["park", "pool", "square"]
},
{
"id": 3,
"name": "wood",
"places": ["church", "garage", "bathroom"]
}
];
const nameObject = document.getElementById('objectName');
const nextBtn = document.getElementById('objectNext');
const list = document.getElementById(`placeList`);
let objectIndex = 0;
nextBtn.onclick = function() {
objectIndex === objects.length - 1 ?
objectIndex = 0 :
objectIndex++;
nameObject.innerHTML = objects[objectIndex].name;
while (list.firstChild) list.removeChild(list.firstChild);
objects[objectIndex].places.forEach(place => {
createPlaceListItem(place);
});
};
const createPlaceListItem = place => {
const $item = document.createElement(`li`);
$item.classList.add(`objectListItem`);
$item.innerHTML = place;
list.appendChild($item);
};
nameObject.innerHTML = objects[objectIndex].name;
objects[objectIndex].places.forEach(place => {
createPlaceListItem(place);
});<h4 id="objectName" class="objectName"></h4> <ul class="objectList" id="placeList"> </ul> <button class="objectNext" id="objectNext">next</button>