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

Does a Javascript event get triggered when the currentSrc attribute of an <img> element is modified?

Let's imagine we have an image tag like this: <img id="my_tag" src="/default.jpg" srcset="/small.jpg 500w, /medium.jpg 1000w, /large.jpg 2000w"> Upon loading the page, JavaScript can determine which source from t ...

What is the best method for expanding the width of a <rect> element with animateTransform?

How can I make a <rect> in SVG expand its width using animateTransform based on a specified value? Additionally, I want the color of the <rect> to change according to the following conditions: If the <rect> value is between 0 and 29: {f ...

creation of cascading drop-down lists

I have been struggling to create a dependent dropdown list using ajax and php, but unfortunately I am not getting the desired outcome. Below is my ajax code: <html> <head> <title>findperson</title> <script type="text/javascript ...

Samsung S4 Android device experiencing interruption in HTML5 video playback

When using Android Webview to play html5 videos, including Youtube videos (using my own tags and Youtube embedded iFrames), I came across an issue with the Samsung Galaxy S4. The problem occurs in the following scenario: Play a video. Press 'back&ap ...

Is it possible to verify if each input is unique using the parsley validator?

As a novice, I am struggling with a task where I have 6 School Children IDs. The teacher needs to input these IDs, and while it's not vital for him to enter all of them, he must input at least one. Furthermore, if he decides to input more than one ID, ...

Updating a component (`AddBudgetModal`) while rendering a different component (`App`) is not possible. To identify the incorrect setState() call within the `AddBudgetModal` component

Here is the code snippet from App.jsx I'm facing an issue on line 44 where I'm attempting to open an addbudgetmodal by passing true or false. However, I'm getting an error message that says "Cannot update a component (App) while rendering a ...

Flex items maintaining their size when the window decreases

My goal is to arrange two plotly plots side by side within a CSS flexbox, with the ability to resize them as the window size changes. The issue I'm facing is that while the plots expand correctly when the window is enlarged, they fail to shrink when t ...

Turning a String array into an array of Integers

Struggling to find a straightforward way to convert my string array into an integer array, I decided to seek out an example method. After some research, here is the approach I came up with: private int[] convert(String string) { int number[] = new int ...

How come the express.static() function is failing to load my .js and .css files from the intended path?

const express = require('express'); const app = express(); const server = require('http').Server(app); const io = require('socket.io').listen(server); const path = require('path'); let lobbies = new Array(); app.us ...

How to implement the ECharts animated bar chart in Angular version 16?

The animated bar chart in ECharts functions perfectly on Stackblitz. You can check it out here in the Stackblitz Angular 16 demo. However, attempting to run the same demo in a local Angular 16 project led to the following errors. Error: src/app/animated- ...

To link various JavaScript files in WordPress

When working on a project in WP 4.2, I am currently adding JavaScript files like this: add_action('wp_print_scripts', array(&$this, 'admin_load_scripts')); ... function admin_load_scripts() { wp_register_script('BackendAr ...

Incorporate a distinct identifier for every menu item within the Material UI TablePagination

Can a unique identifier be assigned to each menu item generated using the <TablePagination> component? I would like to add a specific ID (e.g., id="menu_item_0", id="menu_item_1" & id="menu_item_2") to the menu item ...

Execute the function on the React template rendering process

How can I ensure that the getQuestions function is called when the template questionsCollected is rendered, without relying on an event trigger like onClick? The ajax call successfully retrieves the option items and logs them to the console. The template ...

What is the reason behind not requiring to invoke the next function in a Sails.js controller method, even when it includes an asynchronous database query?

Sample controller function: fetchArticles: function(req, res) { Articles.find({}).exec(function(err, articles) { res.json(articles) // It appears this part is asynchronous // Is next() required here? }) } In my experience, I typicall ...

filter supabase to only show items with numbers greater than or equal to a

Hey there! Currently, I am in the process of setting up a store using nextjs pages router and supabase. However, I have encountered a peculiar bug with my product filtering system when dealing with numbers exceeding 4 digits (e.g., 11000). The structure o ...

Exploring the connections between PHP, JavaScript, JSON, and AJAX

While this question may lean more towards conceptual understanding rather than pure programming, it is essential for me to grasp how these mechanisms interact in order to code effectively. My current knowledge includes: 1) PHP as a programming language ...

Tips for displaying the Material UI Menu component on the left side instead of the default right side

Recently, I created a dropdown component using Material UI's Menu component. However, the default behavior of the menu is to open towards the right side. I actually need it to open towards the left instead. I attempted to modify its styling, and whil ...

Adding a gradient to enhance an SVG chart

Hey there! I'm currently experimenting with Plotly to create some awesome charts, and I've been trying to figure out how to give my area-charts a gradient instead of the usual fill with opacity. This is how I typically build my graph: Plotly.ne ...

Developing an ASP application using the MVP pattern to return JSON data can be transformed into a S

I’m looking to incorporate the following code into a sails js Controller public JsonResult GetEvents() { //Using MyDatabaseEntities as our entity datacontext (refer to Step 4) using (MyDatabaseEntities dc = new MyDatabaseEntities()) { ...

how to use jQuery to hide a flash-containing div without losing its content

Hello, I created a modal with jQuery UI that is displaying in front of a flash movie. However, the HTML content inside the modal appears corrupted. I attempted to hide the movie just before the modal is triggered and make it reappear after closing the mo ...