Is there a way to remove all li elements from a ul list when the button is pressed repeatedly?

When I create a new list item through the DOM and press the button again without refreshing the page, the old elements are not removed. Instead, the new ones are added on top. Any suggestions would be appreciated!

Here is the code snippet for reference:

data.cast.forEach((actors)=>{
                const li = document.createElement('li');
                li.innerHTML = 
                `<li>
                   ${actors.actor}: ${ actors.character} 
                </li>`
                cast.append(li)
            })

Answer №1

In order to add the new, you must first remove the old:

var list = document.getElementById('list');

var items = {
  listItems: [{
    item: "Item01",
    description: "Description of Item01"
  }, {
    item: "Item02",
    description: "Description of Item02"
  }]
};

document.getElementById('refresh').addEventListener('click', e => {
  // Clear the current list
  list.innerHTML = '';
  // Add the new items
  items.listItems.forEach((item) => {
    const li = document.createElement('li');
    li.innerHTML = `${item.item}: ${ item.description}`;
    list.append(li);
  });
});
<ul id="list">
<li>Old item: Old description</li>
</ul>

<button id="refresh">Refresh List</button>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

transferring data from a form with a binary image file to store in an SQL server

I am aiming to create a form where users can upload an image along with some data fields. Currently, I can only get either the image or the data fields to work separately. The following code allows me to upload an image to my SQL database as binary data. I ...

Having difficulty positioning two elements within a button using bootstrap

I am attempting to align two texts horizontally inside a button using Bootstrap 4. The word "Link" keeps getting pushed to the next line and I would like it to stay beside "Copy". I have experimented with using Float but it ends up moving "Link" too far t ...

Can Ajax be utilized to call a PHP script that contains another Ajax function?

I have set up a checkbox that triggers an Ajax call to another PHP script once checked. In this PHP script, there are three text boxes and a button. When the button is pressed, another Ajax call is made to execute yet another PHP script, all within the sam ...

The customized message for parsley's minimum length is not being applied properly when passed as an option during binding

When attempting to bind the Parsley script to an input field, I am encountering an issue with the minlength message not displaying my custom one. Instead, the default error message from Parsley is being shown. I've tried adjusting the code but it does ...

Storing data in cache and refreshing another object for a chart does not function properly

When working in my Controller, I am retrieving data from a $resource object that is stored in a caching service. $scope.data = myService.query(); //myService caches the response. Within the same controller, I am setting up the configuration for a chart ( ...

Parenting and Child Components: Keeping the State in Sync

I am currently diving into my initial React project which focuses on a basic expense tracker for credit cards. While I'm still in the learning phase, I hope you can decipher the intent behind my code. My current roadblock involves mapping the state an ...

Problem encountered when attempting to highlight error message after clicking the "Submit" button without choosing a date

I am facing a challenge with my web application. After clicking the "Submit" button without choosing a date, the error message shows up correctly. However, I've noticed that the text doesn't turn red as expected and the borders don't change ...

Issue with Swiper js "autoheight" not resizing correctly for the height of the first slide upon page initialization

Hey everyone, I'm encountering a problem with my reactapp and I'm not sure how to resolve it. I've spent a considerable amount of time searching on stackoverflow but haven't come across any helpful solutions. The issue is related to a ...

Pinia store encountering a Typescript Vue component issue: error message "The property 'testStore' does not exist on the 'CreateComponentPublicInstance' type."

Within my <script setup> block, I have imported my testStore. However, whenever I attempt to use this.testStore.name in my Vue file, Vetur displays the following error: Property 'testStore' does not exist on type 'CreateComponentPublic ...

Guide on converting HTML datetime picker datetime-local to moment format

I am looking to convert an input type : <input type="datetime-local" name="sdTime" id="stTimeID" onChange={this.stDateTime} /> into a specific date format: const dateFormat = 'MM/DD/YYYY hh:mm:ss a'; To achieve this, I need to transfer ...

The "a" HTML link element is stubbornly resisting being attached to an event listener

I have implemented the MutationObserver observer in my program to monitor the addition of elements. One specific condition I am checking for is if the added element is an anchor tag (tag="a") and if the link is a DOI, then I attach a contextmenu ...

The dropdown on my website is malfunctioning

There seems to be an issue with my dropdown button. Previously, it only appeared when clicking on a specific part of the button. I attempted to resolve this problem but unfortunately, the dropdown no longer works at all and I am unable to revert my changes ...

Error when utilizing the useLocation Hook: "The useLocation() function is only allowed within the scope of a <Router> component" in a React App

Developing a React application has led me to encounter an error while utilizing the useLocation hook from the react-router-dom library. The specific error message reads as follows: Error: useLocation() may be used only in the context of a component. In ...

Confirm that the string is in the correct JavaScript Date format

I'm encountering an issue with validating the specified string obtained from the new Date() Object. "2020-10-06T14:23:43.964Z". I anticipate receiving either this particular input format or a new Date(). My aim is to create something that ca ...

Ways to duplicate the content of a div to the clipboard without the use of flash

Simple question! I have a div identified as #toCopy, along with a button identified as #copy. Can you suggest the most efficient method to copy the content of #toCopy to the clipboard upon clicking #copy? ...

What is the best way to disregard all pathNames and display my index.php file directly from the root of my website?

After a user clicks on a navigation link on my website, the page is loaded into a content window within the same page using JavaScript. I then utilize HTML 5 to modify the URL and create a history entry, resulting in a URL resembling the one mentioned (). ...

Troubleshooting CSS Animation Failure in Internet Explorer 11

My mouse over / mouse out animation works perfectly in Firefox and Chrome, but it's not functioning in IE. Can anyone suggest why this might be happening when it was working fine before? var actual = 1; var over = 0; var over2 = 0; function scrol ...

Incorporating angularjs within a page loaded with jquery.load

Currently, I am in the process of developing a web application designed to cater to multi-device applications. The foundation of this project involves a framework built using nodejs, socket.io, and express which manages the distribution of views. This fra ...

React: Unexpected behavior when modifying a variable's state using post-increment

When I utilize the post-increment operator to change the state variable, the count variable retains its old value... Allow me to illustrate this with an example app: When I click the button with the following code, the app displays the following sequenc ...

Looking to update table content dynamically using jQuery ajax?

I need assistance in creating a dynamic table that can update its content based on the company selected from a dropdown menu. The data should be fetched using AJAX and only display information related to the chosen company. Furthermore, I would like to imp ...