skip to Main Content

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


  1. 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:

    const button = document.getElementById('show_countries');
    const result = document.getElementById('result');
    
    const fetchData = async () => {
      try {
        const response = await fetch('http://localhost:3003/countries');
        const data = await response.json();
        
        console.log(data);
    
        data.forEach(country => {
          const list = document.createElement('li');
          list.textContent = country.name;
          result.appendChild(list);
        })
      }
      catch (err) {
        console.error("error fetching data", err)
      }
    }
    
    const showResult = () => {
      if (result.style.display == 'none') {
        result.style.display = 'block';
        fetchData();
      }
      else result.style.display = 'none';
    }
            
    button.addEventListener("click", showResult);
    Login or Signup to reply.
  2. 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.

     const list = document.getElementById('listId') ? document.getElementById('listId') : document.createElement('li');
     list.innerHtml = "";
     list.id = "listId";
     list.textContent = country.name;
     result.appendChild(list)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search