0

So I made a function to destroy an existing table rows as the page starts , but my problem is that the function is only deleting only 1 row, and going through the loop once.

HTML:

    <div class="rTable">
<div class="rTitleRow">
    <div class="rTableHead"><strong>Producto</strong></div>
    <div class="rTableHead"><strong>Tamanho</strong></div>
    <div class="rTableHead"><span style="font-weight: bold;">Preço</span></div>
    <div class="rTableHead">Quantidade</div>
</div>
<div class="rTableRow">
    <div class="rTableCell">T-shirt World</div>
    <div class="rTableCell">
        <p class="size">L</p></div>
    <div class="rTableCell">
        <p class="cart-price">14.99€</p></div>
    <div class="rTableCell"><input style="width:50px;height: 20px;" type="number" class="quantity" name="quantity"
                                   min="1" value="1">
        <button class="btn-danger">Remover</button>
    </div>
</div>
<div class="rTableRow">
    <div class="rTableCell">T-shirt World</div>
    <div class="rTableCell">
        <p class="size">XS</p></div>
    <div class="rTableCell"><p class="cart-price">14.99€</p></div>
    <div class="rTableCell"><input style="width:50px;height: 20px;" type="number" class="quantity" name="quantity"
                                   min="1" value="1">
        <button class="btn-danger">Remover</button>
    </div>
</div>

js:

var destroytable = function (){

    var tablerows = document.getElementsByClassName('rTableRow')
    length = tablerows.length

    for (var i = 0; i < length; i++) {
       tablerows[i].remove()
       updateCartTotal()
    }
}

destroytable()

2 Answers2

1

try this:

var destroytable = function (){

    var tablerows = document.getElementsByClassName('rTableRow')
    while(tablerows.length > 0) {
      tablerows.item(0).remove();
    }
}

destroytable()
0

When you use remove() function it's shift HTMLCollection indexes, because 0 item was deleted so now 1st item become 0.

console result

The easiest change to make it work use fixed 0 index in your loop

tablerows[0].remove()
Maciek
  • 88
  • 1
  • 10