Reputation: 913
I have a problem with returning rows from html table. can someone guide me how to do it ? I use tbody tag in my table too. I have no clue what am I doing wrong ....
<!DOCTYPE html>
<html>
<body>
<button type="button" onclick="DeleteRow()"> delete </button>
<table id="myTable" >
<thead>
<tr class="header">
<th>1</th>
<th>2</th>
</tr>
</thead>
<tbody>
<tr>
<td> <input type="checkbox" name="check" value="check" class="checkbox"> </td>
<td> 1 </td>
</tr>
<tr>
<td> <input type="checkbox" name="check" value="check" class="checkbox"> </td>
<td> 2 </td>
</tr>
</tbody>
</table>
<script>
function DeleteRow() {
var table = document.getElementById("myTable") ; //table itself
var tableBody = table.getElementsByTagName("tbody") ; //body of table
var rows = tableBody.getElementsByTagName("tr") ; //rows in table-body
document.write(rows.length) ; //wont work
}
</script>
</body>
</html>
Upvotes: 0
Views: 891
Reputation: 2232
.getElementsByTagName()
returns a HTMLCollection (which is like an array :)
function DeleteRow() {
var table = document.getElementById("myTable") ; //table itself
var tableBody = table.getElementsByTagName("tbody") ; //body of table
var rows = tableBody[0].getElementsByTagName("tr") ; //rows in table-body
document.write(rows.length) ; //wont work
}
<!DOCTYPE html>
<html>
<body>
<button type="button" onclick="DeleteRow()"> delete </button>
<table id="myTable" >
<thead>
<tr class="header">
<th>1</th>
<th>2</th>
</tr>
</thead>
<tbody>
<tr>
<td> <input type="checkbox" name="check" value="check" class="checkbox"> </td>
<td> 1 </td>
</tr>
<tr>
<td> <input type="checkbox" name="check" value="check" class="checkbox"> </td>
<td> 2 </td>
</tr>
</tbody>
</table>
<script>
</script>
</body>
</html>
Upvotes: 0
Reputation: 26
If you are trying to put the information into something to he displayed you could use $('#message').html(rows.length); where message would be the I'd of the div you want the information in
Upvotes: 0
Reputation: 207557
Well you are referencing getElementsByTagName on an HTML Collection
var tableBody = table.getElementsByTagName("tbody") <-- HTML COllection
var rows = tableBody.getElementsByTagName("tr") ; <--html collection does not have getEl....
you need to reference an index to use the method
var rows = tableBody[0].getElementsByTagName("tr")
Upvotes: 2