Challenge encountered when attempting to remove elements from an array within a for loop

There seems to be an issue with deleting elements from an array within a for loop.

var div = document.querySelector('div');
var array = [
"iPad",
"iPod",
"iPhone"
];

for (let i = 0; i < array.length; i++) {
  let p = document.createElement('p');
  p.textContent = array[i];
  div.appendChild(p);

  p.onclick = function() {
    array.splice(array.indexOf(this, 1)); 
    this.remove(); 
    console.log(array);
  }

}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
  </head>
  <body>
    
    <div>
      
    </div>
    
  </body>
</html>


It appears that when clicking to delete an item from the array, it deletes items in reverse order. The deletion starts from the last item and works its way up. Any assistance on how to resolve this would be greatly appreciated.

Answer №1

for (let j = 0; j < list.length; j++) {
  let m = document.createElement('p'),
      n = list[j];
  m.textContent = n;
  section.appendChild(m);

  m.onclick = function() {
    list.splice(list.indexOf(n),1); 
    this.remove(); 
    console.log(list);
  }
}

Answer №2

When using

array.splice(array.indexOf(this, 1))
, it's important to remember that this refers to the clicked element while the array contains the text inside that element. To use it correctly, try this approach:

var div = document.querySelector('div');
var array = [
"iPad",
"iPod",
"iPhone"
];

for (let i = 0; i < array.length; i++) {
  let p = document.createElement('p');
  p.textContent = array[i];
  div.appendChild(p);

  p.onclick = function() {
    array.splice(array.indexOf(this.innerHTML), 1); 
    this.remove(); 
    console.log(array);
  }

}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
  </head>
  <body>
    
    <div>
      
    </div>
    
  </body>
</html>

Answer №3

When the onclick function is triggered, implement the following modifications.

p.onclick = function() {
    array.splice(array.indexOf(this.textContent),1); 
    this.remove(); 
    console.log(array);
  }

Answer №4

Take a look at this and this.innerHTML

var div = document.querySelector('div');
var array = [
"Samsung Galaxy",
"Google Pixel",
"OnePlus"
];

for (let i = 0; i < array.length; i++) {
  let p = document.createElement('p');
  p.textContent = array[i];
  div.appendChild(p);

  p.onclick = function() {
array.splice(array.indexOf(this.innerHTML), 1); 
this.remove(); 
console.log(array);
  }

}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
  </head>
  <body>
    
    <div>
      
    </div>
    
  </body>
</html>

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

What are the steps to making a textfield editable with JavaScript and HTML?

My textfield is currently populated with values from the database and is functioning perfectly. I would like to implement a checkbox feature that, when clicked, will clear the textfield of the database values, allowing the user to input new values. If t ...

Using external URLs with added tracking parameters in Ionic 2

I am looking to create a unique http link to an external URL, extracted from my JSON data, within the detail pages of my app. Currently, I have the inappbrowser plugin installed that functions with a static URL directing to apple.com. However, I would lik ...

Surprising block of text suddenly popped up on the browser screen while I was in the middle of working on

Currently delving into the world of MERN stack and working on a simple project. Everything was going smoothly on localhost until out of nowhere, some garbled text appeared on the screen, hindering my progress. I'm completely stumped as to what this my ...

javascript - disable screen capture of specific parts of a webpage

Recently, I've come across certain web pages that have a unique feature preventing screen capture of specific regions. When attempting to take a screenshot using Chrome, some areas that are visible on the live page appear as black frames in the captur ...

The feature of Access Control Request Headers involves appending certain information to the header of an AJAX request when using jQuery

Looking to enhance an AJAX POST request from jQuery with a custom header. Attempted solution: $.ajax({ type: 'POST', url: url, headers: { "My-First-Header":"first value", "My-Second-Header":"second value" } ...

Combine and calculate the total of several columns using the Loadash library

In my Vue application, I am faced with the challenge of grouping an array by date and then calculating sums for multiple columns. The current method I have only allows me to group and sum one column: receiptsByDate: function(){ let byDate = _.groupBy(t ...

Obtaining the value of a command argument with JavaScript in ASP.NET

<asp:LinkButton ID="lnkprogress" runat="server" class="label label-info" BackColor="#589FC2" CommandArgument='<%#Eval("BookingId")%>' OnClientClick="jk();" >In progress</asp:LinkButton> This LinkButton is present in a repeat ...

Introducing the new default in Google Chrome: Now accessing window.opener for target="_blank" links after rel="noopener" is the standard feature

Exploring a new attribute called rel="noopener", I discovered that it keeps opened windows unaware of their opener. After some experimentation, I consistently found window.opener === null, only to realize that this is now the default behavior in ...

Is there a way for me to retrieve the text response of a fetch request from client-side JavaScript to fastify server?

In my fastify node.js application, I am encountering an issue where I can see the text results of a promise right before it is returned to the browser's JavaScript code. However, once the promise is returned to the browser JS, all I get is an empty st ...

When using React-hook-form, you need to tap twice to delete the last character in the input field, and double tap to enter the first

I have been using React Hook Form to validate my form with multiple inputs. Everything works perfectly, except I noticed one issue where I have to press the backspace key twice to delete the last character and also twice to enter the first character. For e ...

What is the process of combining JS functions with PHP echo in code?

I am currently working on creating a popout menu for an array of values that are being displayed from the database. The goal is to show the corresponding popout menu when the svg is clicked, but I am running into an issue where it only works for the first ...

Django and VueJS: Error 403 - Forbidden request due to missing or incorrect CSRF token

My tech stack includes Django and Django REST framework on the backend, along with Vue.js on the frontend. While GET requests function smoothly and POST requests using Postman or Insomnia work fine, encountering an error in the Browser console when sending ...

Communication through HTTP requests is not supported between docker containers

I currently have two applications running as services within a docker-compose environment. My React App A Node.js server In an attempt to make an HTTP request from my React app to the Node.js server, I am using: fetch("http://backend:4000/") However, w ...

What is the best way to organize columns on the front end?

A table needs to be displayed on the front end with the following code snippet: <logic:present name="searchStudent"> <table class=" tblSearchResult" border="1" cellspacing="0" cellpadding="0"&g ...

Increase the number of button groups when clicked

I have a button group with three buttons: left, middle, and right. I want to enhance this functionality so that when any of the main buttons are clicked, the corresponding sub-buttons (left-sub, middle-sub, or right-sub) appear accordingly: <div class= ...

Confirming the validity of an email address with Md-chips

Email Validation for MD-Chips Struggling with creating an email validation for md-chips. The current expression I'm using is not working as expected, since the ng-keypress directive is triggered every time I type something. Any suggestions on how to ...

Switch the view to a grid layout upon clicking

Using bootstrap 5, I've successfully created a list view: <div class="col"> Click to switch to grid/list </div> Below is the content list: <div class="row mt-3 list"> list view ... ..... ....... </div ...

Adjusting the shadow on the inserted image

Currently, I am using fabric.js to manipulate images that are added to my canvas. The issue I am facing is with the shadow around the image not being even. The code I have tried so far is displayed below, but you can view what I am aiming for by clicking h ...

Vuetify offers a convenient solution for implementing multiple buttons in a Vue

My search bar retrieves data from an API query in the following format: Data: [[id, datafield1, datafield2],[id, datafield1, datafield2],...] I wish to include an on/off button for each row of the data, with each button having its own independent state. ...

Troubleshooting problem with transmitting data using the b4j jQuery WebSocket library

I'm seeking guidance on the process of sending data through a custom library that connects to a Java server operating as a WebSocket server. The code I'm using for successful connection is: <script src="https://ajax.googleapis.com/ajax/libs/ ...