0

I have made a function in JavaScript which automatically adds a line to a table every minute. It works fine, except that I would like to delete the second line of the table (since the first line is used for headings) if there are more than 5 lines. I tried this code:

if(table.getElementsByTagName("tr").length > 5){
    table.getElementsByTagName("tr")[1].outerHTML = "";
}

The problem is that when executing the second line, I get an error message saying "unknown execution error". Why does it do that? Is there any way to get around it?

In case it's important, I'm using HTA.

3
  • 1
    Works fine for me (though the second row should be index 1). What browser gives this error? What is HTA? You should provide a full working demonstration of the issue. Commented Mar 8, 2016 at 15:56
  • Also, your headings should really go in a <thead> element and the rest in a <tbody>. Then you can simply do table.tBodies[0].rows[0] to get the row you want. Commented Mar 8, 2016 at 15:59
  • To delete the second row from your table, you can use table.deleteRow(1); Commented Mar 8, 2016 at 16:01

2 Answers 2

1

You can get the number of rows by

var rowCount = document.getElementById("myTable").rows.length;

To delete

if(rowCount > 5) {
    document.getElementById("myTable").deleteRow(1);  //deletes second row
}
Sign up to request clarification or add additional context in comments.

Comments

1

var table = document.getElementsByTagName('table')[0];
if (table.rows.length > 5) {
  table.deleteRow(1);
}
<table>
  <tr><td>1</td></tr>
  <tr><td>2</td></tr>
  <tr><td>3</td></tr>
  <tr><td>4</td></tr>
  <tr><td>5</td></tr>
  <tr><td>6</td></tr>
</table>

(View on Codepen).

  • table.rows returns a collection of all <tr> elements in a table. length is it's property, that returns count of those elements. See Table rows Collection at W3Schools.
  • The deleteRow method removes the row at the specified index of a table. See Table deleteRow() Method at W3Schools.

You can read more about table object in HTML DOM Table Object at W3Schools.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.