0

I Need to delete a table row with pure javascript. The table has only a class name, no id.

Here is a fiddle with my first try:

var table = document.getElementsByClassName('table');
while(table.rows.length > 0) {
    table.deleteRow(1);
}

https://jsfiddle.net/5s0w6cwL/

Thanks for any advice.

Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
MarkusHH
  • 153
  • 13
  • 4
    `var table = document.getElementsByClassName('table')[0]`. See https://jsfiddle.net/5s0w6cwL/1/ – haim770 Jan 30 '17 at 08:55
  • 1
    Possible duplicate of [How to get element by class name?](http://stackoverflow.com/questions/17965956/how-to-get-element-by-class-name) – John Bupit Jan 30 '17 at 09:01
  • Possible duplicate of [How to Get Element By Class in JavaScript?](http://stackoverflow.com/questions/3808808/how-to-get-element-by-class-in-javascript) – user692942 Jan 30 '17 at 21:04

1 Answers1

4

You have to get first element.

var table = document.getElementsByClassName('table')[0];

because document.getElementsByClassName method returns a NodeList.

var table = document.getElementsByClassName('table')[0];
table.deleteRow(1);
<table class="table" border="1">
    <tbody>
        <tr>
         <td>&nbsp;</td>
        </tr>
        <tr>
         <td>delete me</td>
        </tr>
        <tr>
         <td>&nbsp;</td>
        </tr>
    </tbody>
</table>
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128