Home > OS >  How to remove an item using class? : javascript
How to remove an item using class? : javascript

Time:08-28

I made a table to show some items and i want it to be cleared once i press the clear button. Now the main problem is that my tr that i want to remove does'nt take tbody as its parent. Here's my html:

<table>
    <tbody id="stuffCarrier"></tbody>
</table>

and here's my javascript to remove the items:

document.getElementById("clearList").onclick = function () {
Array.from(document.getElementsByClassName("removeds")).forEach((e, i, arr) => {
    document.getElementById("stuffCarrier").removeChild(e);
    console.log(i, e, e.parentElement, arr);
});
localStorage.removeItem("CarriedStuff");

And here's my javascript how i added the items:

    const stuffCarrier = document.getElementById("stuffCarrier");
stuffCarrier.innerHTML = `<tr>
<th >Quantity</th>
<th  style="color:red">Stuff</th>
<th  style="color:chartreuse">Cost</th>
</tr>
`;

showStuff.forEach(e => {
    stuffCarrier.innerHTML  = `<tr >
    <td>${e[2]}</td>
    <td style="color:blue">${e[0]}</td>
    <td style="color:white">${e[1] * e[2]}</td>
    </tr>
    `;
});

CodePudding user response:

Array.from(document.getElementsByClassName("removeds")).forEach(d=>d.remove())

CodePudding user response:

First try to add tr as childElement of stuffCarrier like this:

const stuffCarrier = document.getElementById("stuffCarrier");
childElement = `<tr>
<th >Quantity</th>
<th  style="color:red">Stuff</th>
<th  style="color:chartreuse">Cost</th>
</tr>
`;

stuffCarrier.appendChild(childElement);

Even within the for loop. Then I think you will be able to remove tr as removeChild().

Or you can directly remove all the selected elements like this:

Array.from(document.getElementsByClassName("removeds")).forEach(d=>d.remove()) without using removeChild() method.

I hope it helps.

CodePudding user response:

you need a closing function bracket before the localstorage line, but other than that it works??

<input id='clearList' value='clear' type='button' />
<table>
    <tbody id="stuffCarrier"></tbody>
</table>
<script>
    var showStuff=[
      [1,2,3],[4,5,6]
    ]

    const stuffCarrier = document.getElementById("stuffCarrier");
    stuffCarrier.innerHTML = `
    <tr>
      <th >Quantity</th>
      <th  style="color:red">Stuff</th>
      <th  style="color:chartreuse">Cost</th>
    </tr>
    `;

    showStuff.forEach(e => {
        stuffCarrier.innerHTML  = `
        <tr >
          <td>${e[2]}</td>
          <td style="color:blue">${e[0]}</td>
          <td style="color:cyan">${e[1] * e[2]}</td>
        </tr>
        `;
    });


    document.getElementById("clearList").onclick = function () {
        var nl=document.getElementsByClassName("removeds");
        Array.from(nl).forEach((e, i, arr) => {
            document.getElementById("stuffCarrier").removeChild(e);
            console.log(i, e, e.parentElement, arr);
        });
    }
</script>  

  • Related