Home > Mobile >  How to remove a particular item from an array?
How to remove a particular item from an array?

Time:10-11

My Dom is like this :

       <div class="child">
            child1
            <button class="btn">Delete</button>
        </div>
        <div class="child">
            child2
            <button class="btn">Delete</button>
        </div>
        <div class="child">
            child3
            <button class="btn">Delete</button>
        </div>
        <div class="child">
            child4
            <button class="btn">Delete</button>
        </div>

Now my js like this :

const btn = document.querySelectorAll('.btn');
btn.forEach((button, i)=>{
    button.addEventListener('click', ()=>{
        const boxes = document.querySelectorAll('.child');
        boxes.splice(i, 1)
    })
})

Now boxes is an array and after clicking on delete button I want to remove The pertucal item from that arrray. but it says boxes.splice() is not a function. how to solve this?

CodePudding user response:

splice() is an array method. The collection returned from querySelectorAll() is Array-like. Use something like ... spread operator to convert it to an array.

const btn = document.querySelectorAll('.btn');
btn.forEach((button, i)=>{
    button.addEventListener('click', ()=>{
        const boxes = [...document.querySelectorAll('.child')];
        boxes.splice(i, 1)
    })
})

Note: This doesn't actually delete anything from the DOM. Only removes it from the array as you have indicated in the question.

CodePudding user response:

The querySelectorAll returns a noed list You have to convert it to an array

const nodelist = document.querySelectorAll('div');
const nodelistToArray = Array.apply(null, nodelist);

CodePudding user response:

Now boxes is an array and ...

Actually, boxes is NOT an array, as you think. boxes is the result of document.querySelectorAll, which returns a NodeList, not an array. A NodeList is very similar to an array, but it doesn't have all of the methods of Array.prototype. To use .splice on a NodeList, you have to convert it to an array. Here is how you would do that:

const btn = document.querySelectorAll('.btn');
btn.forEach((button, i) => {
  button.addEventListener('click', () => {
    const boxes = Array.from(document.querySelectorAll('.child'));
    console.log(boxes.splice(i, 1));
  });
});
  • Related