What is the best way to delete only the current occurrence of the array, without removing all other instances?

Is there a way to remove only the current instance of the array, without affecting all other instances?

var persons = [];

showAllButton.onclick = function() {

  while (showList.firstChild) showList.removeChild(showList.firstChild);

New node instances have been created.

for (var l in persons) {
    var listNode = document.createElement("LI");
    var btn = document.createElement("BUTTON");
    btn.innerHTML = "Remove";
    showList.appendChild(listNode);
    showList.appendChild(btn);

The pushed instances are displayed correctly.

listNode.innerHTML =
    '<p><b>Full Name:</b> ' + persons[l].firstName +' ' + persons[l].lastName + '</p>' +
    '<p><b>Phone:</b> ' + persons[l].phone + '</p>' +
    '<p><b>Address:</b> ' + persons[l].address + '</p>'
    }

I've tried various versions of the following function but it either clears the entire array or doesn't return the updated array.

btn.onclick = function() {
        var index = Array.indexOf(persons[l]);
        persons.splice(index, 1);              
        return persons;
    }



if (showAllButton.value=="Show Contacts") {
    showAllButton.value = "Hide Contacts";
    showList.style.display = "block";   
}


else if (showAllButton.value = "Hide Contacts") {
    showAllButton.value = "Show Contacts";
    showList.style.display = "none";  
}     

}

Answer №1

It may be more efficient to bind the value of l, delete the element at index l, and then refresh the DOM in some way:

btn.onclick = function(l) { //binding the value of l
    persons.splice(l, 1);              
    //need to redraw the content on the DOM somehow
    showAllButton.click();
}.bind(null,l);//value of l bound

Answer №2

Here's a quick solution that should work as intended (apologies for the rushed code, no time to test at the moment)

var individuals = [];
function eliminateIndividual(index) {
    individuals.splice(index, 1);
    displayList();
}

function clearList() {
    while (displayedList.firstChild) {
        displayedList.removeChild(displayedList.firstChild);
    }
}

function showPerson(person, index) {
    var item = displayedList.appendChild(document.createElement("LI"));

    var label = item.appendChild(document.createElement("SPAN"));
    label.innerHTML = individuals[i];

    var btn = item.appendChild(document.createElement("BUTTON"));
    btn.innerHRML = "Remove";
    btn.onclick = removePerson.bind(null, index);
}

function renderList() {
    clearList();
    individuals.forEach(renderItem);
}

It may not be the most efficient code, but it appears to be functioning.

Answer №3

Code successfully implemented, much appreciated!

showAllButton.onclick = function() {

while (showList.firstChild)showList.removeChild(showList.firstChild);

for (var i in persons) {
var list = showList.appendChild(document.createElement("LI"));
list.innerHTML =
'<p><b>Full Name:</b> ' + persons[i].firstName +' ' + persons[i].lastName + '</p>' +
'<p><b>Phone:</b> ' + persons[i].phone + '</p>' +
'<p><b>Address:</b> ' + persons[i].address + '</p>';

var btn = showList.appendChild(document.createElement("BUTTON"));
btn.innerHTML = "Remove";
btn.onclick = function(i) {
     persons.splice(i, 1);
     showAllButton.click();

}.bind(null,i);

}

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

Removing div elements containing specific text using jQuery

Hello everyone, I am trying to remove all divs that contain a specific part of a string. Does anyone know how I can do this? This is what my original HTML looks like: <div class="article-options_4"></div> And this is the new HTML structure, ...

Function triggered by onmouseover continues to trigger repeatedly upon mouse hover

I have a function that activates when the mouse hovers over a div. Inside the div, there is a link that spans 100% of its height and width. This link contains an image that the function moves when the grandparent (the div) is hovered over. The function m ...

Techniques for adding values to arrays in JavaScript

My Anticipated Result let Album = { album_desc: AlbumTitle, id: 1, album_title: 'ss', AlbumDescription: 'sdsd', ImageName: 'image.jpg', album_pics: below array }; I am looking to dynamically p ...

Creating a new line in the content of a MatDialog in Angular 7

I have a situation where I am using MatDialog and attempting to insert a new line in the content definition. I've tried using both \n and </b>, but neither of them seem to work. Is there an alternative way to achieve this without manually e ...

Trouble with minified scripts on a particular server

Apologies if this has already been addressed, but I've been searching for a solution for hours. I created a basic website that works perfectly on my own hosting. However, when I transfer it to new hosting (same company, same package, different server ...

Utilizing `v-model` on a component that contains `<script setup>` in Nuxt can cause issues with the standard `<script>` tags

Working on a Nuxt3 project, I have implemented v-model on a component. Following the guidance from Vue documentation, here is how it should be done: In the parent component: <MyInput v-model="myData" placeholder="My placeholder" /&g ...

The Blender model imported into Three.js appears to have been rendered in a lower resolution than expected

I recently brought a gltf model into my Three.js project, which was exported from Blender. The model appears perfectly rendered in , but in my Three.js project, it seems to have lower quality as depicted in these screenshots: https://ibb.co/qrqX8dF (donm ...

Is there a way to trigger an offclick event after an onclick event?

I am currently developing a virtual keyboard specifically designed for touchscreen computers. Utilizing angular, html, and css exclusively in this project. I am facing an issue where holding down a key does not properly lift up the mouse click event. How c ...

Access any nested node within a JSON/JS object by specifying the key's value

After spending hours searching on various forums for a solution to my problem, I have yet to find one that directly addresses the issue I am facing. So, please take a moment to review the details below. The object structure in question is as follows: let ...

What is the best way to retrieve the component object of the child components I am rendering in a list?

Within my component, I have a JSON payload containing a service. However, I am unsure of the best way to access the list items component objects from the parent component. ...

Transmitting data from the front end to the server in React/Shopify for updating API information using a PUT request

After successfully retrieving my API data, I am now tasked with updating it. Within my component, I have the ability to log the data using the following code snippet. In my application, there is an input field where I can enter a new name for my product an ...

What steps can be taken to ensure the random generator continues to function multiple times?

My little generator can choose a random item from an array and show it as text in a div. However, it seems to only work once. I'm looking for a way to make it refresh the text every time you click on it. var items = Array(523,3452,334,31,5346); var r ...

What could be causing this code to malfunction on a mobile device?

I am struggling to make this drag and drop function work on mobile devices. Despite implementing the code, it doesn't seem to function properly when accessed on my mobile phones. Here is the snippet of the code: copy = 1; $('.dragArea img&apo ...

"Step-by-step guide on setting up routing in React using Redux for navigating to and from the root file (index

I am working on a React server webpage and I am trying to set up redirects from index.js (localhost:3000) to the Login page (localhost:3000/login), and from login back to index in case of a failed login attempt. Can you help me with what code I need to inc ...

Synchronizing Database with Javascript

I've been developing a real-time JavaScript Application that necessitates immediate synchronization between the database and JavaScript. Currently, whenever there are changes in JavaScript, an ajax call is made to the API to update the DOM accordingl ...

Checking the condition prior to adding an item and displaying a message in ReactJS

I am currently working on an application using React.JS Before adding data, I want to implement a condition check. This is the code snippet: const App = () => { const [item, setItem] = useState([]) const [category, setCategory] = useState([]) ...

Prevent AJAX request while in progress?

I've made some adjustments to a jQuery Autocomplete plugin, which now retrieves a JSON object from a MySQL database instead of an array. However, I've noticed that each time I click on the input field, it triggers a new request, even if it&apos ...

Troubleshooting a lack of color in the D3 and Leaflet Circle SVG element

I need to showcase some SVG circle elements on a map using d3. Here is the code for one of the circles positioned over Rome, styled with D3 attributes: var feature = g.append("circle") .style("stroke", "#006600") .style("fill", "#00cc00") .at ...

Creating dynamic animations in three.js involves using time as a crucial

As someone who is new to Javascript, I am struggling to understand how the time argument functions within the animate function provided below. It seems that the animate function requires a time argument, but when called as a callback in setAnimationLoop, ...

Exploring the possibilities of event-driven programming with Java and Javascript?

When performing computations on a server, the client inputs data that is captured through Javascript. A XMLHttpRequest is made to send this data to the server for processing. What happens if the computation takes an hour and the client leaves or switches o ...