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!