Deleting an element from an array in JavaScript by its index

I'm currently working on a todo type app and I need to figure out how to remove an array element. Adding elements using element.push() is straightforward, but removing them is a bit more challenging. The remove button is nested within a template literal in a for loop, which complicates things. I've come across another method that uses

node.parentNode.removeChild(node);
, but since this involves an array data structure, I suspect the approach will be different. This project serves as a learning playground for me, so any help would be appreciated. Here's what my code looks like:

const main = document.querySelector('.app');
const header = document.createElement('DIV');
const hero = document.createElement('DIV');
const heading = document.createElement('H1');
heading.textContent = 'Heading Tag';
main.before(heading);

const data = [
  "Monday",
  "Tuesday",
  "Wednesday",
  "Thursday",
  "Friday"
];

// Code continues...

let removeItem = document.getElementById('removeItem');
removeItem.addEventListener('click', (data) => {

  for (let i = 0; i < removeItem.length; i++) {
    data.splice(i, 1);
  }
});

Could indexOf be a viable solution here?

Answer №1

I have successfully implemented your code and made some enhancements from line 86 to 120.


const container = document.querySelector('.main');
const topSection = document.createElement('DIV');
const bottomSection = document.createElement('DIV');
const headline = document.createElement('H1');
headline.textContent = 'Main Heading';
container.before(headline);

var items = [
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday"
];

const addTopSection = () => {
topSection.textContent = 'Top Section Title';
topSection.classList.add('top-section');
topSection.innerHTML = '<div class="innerContent">Inner Content</div>';
topSection.setAttribute(
 "style", "font-size: 32px; font-style: italic; background-color:#ff0000; color: white; width: 100%; height: 200px; padding: 20px; font-family: sans-serif"); 
container.append(topSection);
}

const addBottomSection = () => {
    bottomSection.textContent = 'Bottom Section Title';
    bottomSection.classList.add('bottom-section');
    bottomSection.innerHTML = '<div class="innerBlock">Inner Block</div>';
    bottomSection.setAttribute(
     "style", "font-size: 32px; font-style: italic; background-color:#000000; color: white; width: 100%; height: auto; padding: 20px; font-family: sans-serif"); 
    container.append(bottomSection);
}

 const generateListItems = (elements) => {
    let list = ''; 
    for (let i = 0; i < elements.length; i++) {
        list += `<li>${elements[i]}</li><button type='button' class='removeItem'>Remove Item</button>`;

    }
    return list;
    
    }

const arrangeContent = () => {
    const layout = addTopSection() + addBottomSection();
}
arrangeContent();


const addToItemList = () => {
    const addButton = document.getElementById('addButton');
    const inputField = document.getElementById('input').value;
    items.push(inputField);    
    updateHTML(items);  
}

const removeLastItem = () => {
    items.pop(items);    
    updateHTML(items);  
}

const removeFromSpecificIndex = (index) => {
// One-liner code to remove an element in an array, feel free to ask if you need clarification.
        (index > -1) ? items.splice(index, 1) : false;
        updateHTML(items);
}

const updateHTML = (items) => {
    let finalHtml = `
    <ul>
        ${generateListItems(items)}
    </ul>
    <input type='input' id="input" required></input><button type='button' id='addButton'>Add item</button><button id='removeButton'>Remove item</button>
    `
    document.querySelector('.bottom-section').innerHTML = finalHtml;

    addButton.addEventListener('click', () => {
        addToItemList();
    });

    removeButton.addEventListener('click', () => {
        removeLastItem();
    });

    listenToClicks("removeItem", function(index) {
        removeFromSpecificIndex(index);
    })
 }  

function listenToClicks(className, action) {

    // Apply click handler to all elements with matching className
    var allElements = document.body.getElementsByTagName("*");

    for(var x = 0, len = allElements.length; x < len; x++) {
        if(allElements[x].className == className) {
            allElements[x].onclick = handleClick;
        }
    }

    function handleClick() {
        var parentElement = this.parentNode;
        var childrenOfParent = parentElement.childNodes;
        var index = 0;

        for(var x = 0; x < childrenOfParent.length; x++) {
            console.log(childrenOfParent[x]);
            if(childrenOfParent[x] == this) {
                break;
            }

            if(childrenOfParent[x].className == className) {
                index++;
            }
        }

        action.call(this,index);
    }
}

 updateHTML(items);

This method was inspired by the solution found in Get clicked class index javascript

The listenToClicks() function sets up an event listener on an HTML tag and provides the index of that tag relative to others with the same name.

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

Tips for Keeping Sub Menu Visible Without Having to Click

I am working on an HTML navigation menu that opens submenus on click like this... $("#nav_evnavmenu > li > a").click(function () { // bind onclick if ($(this).parent().hasClass('selected')) { $("#nav_evnavmenu .selected div div ...

Ways to display multiple PHP pages in a single division

Within my project, I have a unique setup involving three distinct PHP pages. The first file contains two divisions - one for hyperlinked URLs and the other for displaying the output of the clicked URL. Here is an excerpt from the code snippet: <script& ...

Using NextJS to render a Link component by creating an element

Struggling to use createElement in NextJS to render a Link, but facing issues. Code: import {createElement} from "react"; import Link from "next/link"; createElement( item.href ? Link : "div", { href: item.hre ...

The value of a variable decreases upon being utilized in an Ajax API call

My tempid variable seems to lose some of its values when passed into the second API call. Despite logging the variable to console (console.log(tempid)) where it appears fine, once placed in the API call it only retains some of its value. I'm uncertain ...

Utilize jQuery to interact with a Web API web service

Okay, so go ahead and roast me in 27 different languages if you want, but here's my dilemma: I've delved into creating a web service using the .NET 4 Web API. I've coded a method named GetTransaction that simply returns a string. It's ...

Guide to making a dropdown menu that pulls information from a text box and displays the location within the text

I'm currently working on a unique dropdown feature that functions like a regular text field, displaying the text position. To achieve this, I've constructed a hidden dropdown menu positioned beneath the text field. My goal is to develop a jQuery ...

Using jQuery, how can I dynamically change the stacking order of an element when clicked?

I'm struggling to change the z-Index on button click. I have a static image and a dynamic div, and I want to send the #imgDiv1 behind the static image. Unfortunately, despite trying everything, I haven't been able to achieve this. You can check ...

When should vuex be used for storing data instead of relying on local component data?

Currently I am tackling a complex project that is built using Vue. Our team has opted to use Vuex as our state management system, however there are certain components where the data is not needed elsewhere. Should I follow convention and store this data ...

retrieving multiple values in ajax call and processing them in controller function

I'm facing a challenge in Laravel when it comes to sending multiple input options (generated by a foreach loop) through an ajax call. The goal is to send multiple values and loop through them in the ajax call to effectively pass them to the controller ...

Using jQuery to target form elements that have a specific class assigned to them

I am facing an issue with targeting input fields within a specific form on a page. The form has a certain class, let's say "has-error," and I want to remove this class from all the input fields in that form. I attempted the following code snippet: t ...

Is there a way to pass attributes to BufferGeometry in THREE.js without using ShaderMaterial?

I've been attempting to make a THREE.js example designed for version 58 compatible with the latest version of THREE.js. You can find the original example here. While I was able to resolve a few errors by simply commenting out certain code, one error ...

Conceal the scroll bar while still allowing for scrolling functionality

In this code snippet, I am trying to maintain the scroll position of two blocks by syncing them together. Specifically, I want to hide the scrollbar of the left block while scrolling the right one. If anyone has any suggestions or solutions for achieving ...

Detecting repeated keys in a query for a REST connector in loopback

Can anyone help me figure out how to duplicate parameters in a loopback REST connector query? Here's the code snippet I'm working with: details: { 'template': { 'method': 'GET', 'debug': tr ...

Avoiding an endless JavaScript loop in Selenium/PhantomJS to improve test automation sanity

Imagine a scenario where a web application contains JavaScript code like the one below: for(i=0; i > -1; i++){var a=1}; // Infinite loop If I attempt to navigate this web app using Selenium or PhantomJS, it will become unresponsive indefinitely. Is t ...

Create an index.html file using webpack to utilize it with the development server

Using webpack to run my Three.js application, I have the following configuration in the webpack.config file: module.exports = { entry: `${__dirname}/src/tut15.js`, output: { path: __dirname + '/dist', filename: 'index_bundle.js&a ...

Opening a Bootstrap Modal in React without relying on npm react-bootstrap

I've been trying to create a Modal in React.js using Bootstrap5, but I'm unable to use npm react-bootstrap for various reasons. I attempted an approach where I utilized state to set Modal classes with a button, which worked well with my NavBar, b ...

What is the best way to iterate over my JSON data using JavaScript in order to dynamically generate cards on my HTML page?

var data = [ { "name":"john", "description":"im 22", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4c7d7e7f0c2b212d2520622f">[email protected]</a>" }, { "name":"jessie", ...

Utilize strings as object keys in JavaScript

Let's say I have the following variables: var myKey = "This_is_my_key" var myObj = {"This_is_my_key" : true} What is the proper way to access myObj using the key myKey? ...

Using Angular 2 routes to navigate to various applications

I'm currently developing multiple versions of my application in different languages. Utilizing AOT (ahead of time) compilations, the end result is static deployable sites organized in a structure like this: dist - index.html -- default entry file f ...

Problem with PHP function

Attempting to create a database-driven menu based on parent-child relationships. All root menu items have a parent column value of 0. Continuously encountering the following errors: Undefined offset: 0,1,2 on line list($id, $parent, $name) = $results; ...