1

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?

Umutambyi Gad
  • 4,082
  • 3
  • 18
  • 39
Sole
  • 3,100
  • 14
  • 58
  • 112
  • 2
    You can use array method `splice()` with array `indexOf(element)` method like this: `array.splice(array.indexOf(object),1);` – user3647971 Jul 04 '20 at 12:10
  • So there's couple things to know what that does. First off the indexOf method searches for that exact same object it is passed as parameter from the array then returns the index -1 if it's not found or the corresponding array index for that object. Second, you would have to either store the array index somewhere to use splice separately of indexof, or have your removeItem array contain the exact same objects as data and use the object with indexOf. However with your code you are using same id on every removeItem button you create. They should be unique. – user3647971 Jul 04 '20 at 12:25

1 Answers1

1

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.

cerebrus6
  • 86
  • 8