In this tutorial we will learn How to Get table row Height with JavaScript. For this we can use offsetHeight property or clientHeight property with the rows property and getElementById() method.
Table of Contents
offsetHeight property
offsetHeight property returns the height of HTML element including content, padding, border and scrollbar.
margin height is not included.
We can use offsetHeight property to get the height of table row in pixels.
clientHeight property
clientHeight property returns the height of HTML element including content and padding.
Height of margin, border and scrollbar are not included.
We can also use clientHeight property to get the table row height but it won't include margins and border.
rows property
rows property returns all rows of the selected HTML table.
rows[index] is used to target the row by it's index, where index starts from 0.
getElementById() method
getElementById() method is used to select HTML element by it's id.
In this example getElementById() method is used to select HTML table.
HTML Code
HTML Code is given below, in this code we have a table tag with four rows and a button.
<!DOCTYPE html>
<html>
<head>
<title>Get table row Height JavaScript</title>
<style>
table,tr,th,td
{
border: 1px solid black;
margin: 10px 0px;
padding: 5px;
}
table
{
border-collapse: collapse;
}
</style>
</head>
<body>
<table id="table">
<tr>
<th>Day</th>
<th>Teacher</th>
<th>Class</th>
</tr>
<tr>
<td>Monday</td>
<td>Mark</td>
<td>HTML</td>
</tr>
<tr>
<td>Wednessday</td>
<td>Jake</td>
<td>CSS</td>
</tr>
<tr>
<td>Friday</td>
<td>Jason</td>
<td>JavaScript</td>
</tr>
</table>
<button onclick="getRowHeight()">Get Row Height</button>
<script src="script.js"></script>
</body>
</html>
JavaScript Code
Take a look at the JavaScript code, In this code user defined function getRowHeight() will calculate the height of table row.
rows[0] represents first row, while for second row we can use rows[1] and so on.
Code to measure height of first row.
<script>
function getRowHeight()
{
var table = document.getElementById('table');
var rows = table.rows;
var height = rows[0].offsetHeight + "px";
alert(height);
}
</script>
To measure height of second row.
<script>
function getRowHeight()
{
var table = document.getElementById('table');
var rows = table.rows;
var height = rows[1].offsetHeight + "px"; // for second row
alert(height);
}
</script>
Measure row height using clientHeight property.
<script>
function getRowHeight()
{
var table = document.getElementById('table');
var rows = table.rows;
var height = rows[0].clientHeight + "px";
alert(height);
}
</script>
Demo
Video Tutorial
Watch video tutorial on how to Get table row Height using JavaScript.