Sole
Sole

Reputation: 3340

Remove array element using index in JS

I would like to remove an array element from my todo type app. Adding is fine using element.push(). The remove button is in a template literal in the for loop. So I don't quite understand how to remove the element. I do now of another method using node.parentNode.removeChild(node); but as this is an array data method I assume the approach would be different. This is more of a learning/playground project for me. My code so far is:

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"
];

const headerElement = () => {
  header.textContent = 'Header';
  header.classList.add('header');
  header.innerHTML = '<div class="innerElement">Inner</div>';
  header.setAttribute(
    "style", "font-size: 32px; font-style: bold; background-color:#ff0000; color: white; width: 100%; height: 200px; padding: 20px; font-family: sans-serif");
  main.append(header);
}

const heroElement = () => {
  hero.textContent = 'Hero';
  hero.classList.add('hero');
  hero.innerHTML = '<div class="innerElement">Inner Element</div>';
  hero.setAttribute(
    "style", "font-size: 32px; font-style: bold; background-color:#000000; color: white; width: 100%; height: auto; padding: 20px; font-family: sans-serif");
  main.append(hero);
}

const itemArray = (ele) => {
  let items = '';
  for (let i = 0; i < ele.length; i++) {
    items += `<li>${ele[i]}</li><button type='button' id='removeItem'>Remove Item</button>`;

  }
  return items;

}

const layOut = () => {
  const ui = headerElement() + heroElement();
}
layOut();


const addItemFunction = () => {
  const addButton = document.getElementById('addButton');
  const input = document.getElementById('input').value;
  data.push(input);
  htmlInside(data);
}

const removeItemFunction = (index) => {
  const removeButton = document.getElementById('removeButton');
  data.pop(data);
  htmlInside(data);
}

const htmlInside = (data) => {
  let getHtml = `
        <ul>
            ${itemArray(data)}
        </ul>
        <input type='input' id="input" required></input><button type='button' id='addButton'>Add item</button><button id='removeButton'>Remove item</button>
        `
  document.querySelector('.hero').innerHTML = getHtml;

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

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

htmlInside(data);

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

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

I was thinking maybe using indexOf?

Upvotes: 1

Views: 208

Answers (1)

cerebrus6
cerebrus6

Reputation: 96

This works, I've worked on your code and added something in line 86 to 120.


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);

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

const headerElement = () => {
header.textContent = 'Header';
header.classList.add('header');
header.innerHTML = '<div class="innerElement">Inner</div>';
header.setAttribute(
 "style", "font-size: 32px; font-style: bold; background-color:#ff0000; color: white; width: 100%; height: 200px; padding: 20px; font-family: sans-serif"); 
main.append(header);
}

const heroElement = () => {
    hero.textContent = 'Hero';
    hero.classList.add('hero');
    hero.innerHTML = '<div class="innerElement">Inner Element</div>';
    hero.setAttribute(
     "style", "font-size: 32px; font-style: bold; background-color:#000000; color: white; width: 100%; height: auto; padding: 20px; font-family: sans-serif"); 
    main.append(hero);
}

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

    }
    return items;
    
    }

const layOut = () => {
    const ui = headerElement() + heroElement();
}
layOut();


const addItemFunction = () => {
    const addButton = document.getElementById('addButton');
    const input = document.getElementById('input').value;
    data.push(input);    
    htmlInside(data);  
}

const removeItemFunction = (index) => {
    data.pop(data);    
    htmlInside(data);  
}

const removeSpecificItemFunction = (index) => {
// This is a one liner code to remove an element in an array, I hope you can understand. If you can't, just ask.
        (index>-1) ? data.splice(index, 1) : false;
        htmlInside(data);
}

const htmlInside = (data) => {
    let getHtml = `
    <ul>
        ${itemArray(data)}
    </ul>
    <input type='input' id="input" required></input><button type='button' id='addButton'>Add item</button><button id='removeButton'>Remove item</button>
    `
    document.querySelector('.hero').innerHTML = getHtml;

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

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

    clickedClassHandler("removeItem", function(index) {
        removeSpecificItemFunction(index);
    })
 }  

function clickedClassHandler(name,callback) {

    // 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 == name) {
            allElements[x].onclick = handleClick;
        }
    }

    function handleClick() {
        var elmParent = this.parentNode;
        var parentChilds = elmParent.childNodes;
        var index = 0;

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

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

        callback.call(this,index);
    }
}

 htmlInside(data);

This is good a method I got from Get clicked class index javascript

clickClassHandler() creates an event handler to an HTML tag and returns an index of that tag in relation to other tags of the same name.

Upvotes: 1

Related Questions