Im new to coding and stuck. Im creating a list when a button is clicked. the data for the list is coming from my backend server. Now when i click the button again another set of list data is added on top of the existing ones. How do i make the function add a list of data when pressed but delete the list when it is clicked again. here is my code
const button = document.getElementById(‘show_countries’);
const fetchData = async () => {
try {
const response = await fetch(http://localhost:3003/countries
);
const data = await response.json();
console.log(data);
const result = document.getElementById('result');
data.forEach(country => {
const list = document.createElement('li');
list.textContent = country.name;
result.appendChild(list)
})
} catch (err) {
console.error("error fetching data", err)
}
}
button.addEventListener("click",fetchData);
2
Answers
you can use popup, so you should set a class such as display:none; for result element to hide this and when button clicked, add the lists and then display it. for example:
youre creating an element "li", but not assigning an ID to that element.
my suggestion is to assign an id to it so that you can later access it and modify it.
then your code should first try and find ‘listId’, delete its contents, then reset the contents.