DotNetCurry Logo

HTML Table and jQuery – Handy Code Snippets

Posted by: Suprotim Agarwal , on 4/17/2016, in Category jQuery and ASP.NET
Views: 8755
Abstract: Some jQuery code snippets that will be useful while working with HTML Tables.

Here are some handy code snippets that will be useful while working with HTML Tables.

1 - Highlight a cell/row based on a value

Let us see how to highlight some cells or rows in a HTML Table and grab the user’s attention. Create a HTML file called ‘MiscTableFunctions.html’  and add the following markup:

< table id="someTable">
    < thead>
        < tr>
            <th class="empid">EmpId</th>
            <th class="fname">First Name</th>
            <th class="lname">Last Name</th>
            <th class="email">Email</th>
            <th class="age">Age</th>
        </ tr>
    </ thead>
    < tbody>
        < tr>
            <td class="empid">E342</td>
            <td class="fname">Bill</td>
            <td class="lname">Evans</td>
            <td class="email"></td>
            <td class="age">35</td>
        </ tr>
    </ tbody>
</ table>

We will be use the following css for highlighting the cells/rows:

    font-weight: bold;
    color: #0a9600 !important; 

Now write some code that highlights a cell if the employee’s age is > 50.

$(function () {
    $("#someTable td.age").filter(function () {
        return parseInt($(this).text(), 10) > 50;

The selector $("#someTable td.age") selects all td’s with the class age.Using .filter() we reduce the set of matched age cells to those cells that have a value greater than 50. We are using parseInt() first to convert the text in each age cell, to a number, and then comparing to see if the text is greater than 50. The class ‘highlite’ highlights all age cells which has a value > 50, by changing the color of the matching cell, to bold green.

If you observe, the parseInt function has two arguments: a required numeric string, and an optional radix (base). The radix is the number’s base, as in base-8 (octal), base-10 (decimal) and base-16 (hexadecimal). If the radix is not provided, it’s assumed to be 10, for decimal. Although the second argument is optional, it’s considered a good practice to always provide it explicitly.

Save and browse the file in your browser and the Age cell in the 3rd row gets highlighted.


If you want to highlight the entire row instead of just a cell, use parent()

$("#someTable tbody tr td.age").filter(function () {
    return $(this).text() > 50;

parent() gets the parent of each age cell in the current set of matched elements. Since the parent of the cell is a row, the entire row gets highlighted.


Live Demo:

2 - Count Number of Rows in a Table

To count the total number of rows, use the following code:

$("#someTable").after(function () {
    console.log($('tr', this).length + " rows.");

A typical approach to this requirement is to loop through the rows using each() and then count it. I am instead using .after() which will return all DOM elements inside the table. Instead of using find(‘tr’).length() function to count the number of rows, I am using jQuery's context parameter $('tr', this) which gives better performance. this here refers to the table. If you are using Chrome, open the JavaScript console using Ctrl + Shift + J (Cmd+Opt+J on Mac) and view the page.


You must be wondering why we are getting the count as 6 rows, when the table contains only 5 rows. We get 6 rows as the <thead> also has a <tr>. To get the correct count, simply change the selector from $("#someTable") to $("#someTable tbody") which will now select only rows inside the tbody.

3 - Add a New Row Below the Selected Row by Clicking on It

If your table emulates a spreadsheet, you may want to give your users the option to add new rows to the table at runtime. Here’s how to do so:

$(function () {
    $("#someTable tbody").on("click", "tr", function (e) {
        if ( != "text") {
            var row = $("<tr><td><input /></td><td>-</td><td>-" +

Although we can wire up the code to execute on a button click, I am letting the users create new rows by clicking on any row in the table. On click, we are getting a reference to the clicked row and then using after() to insert the new row, after the row that was clicked. Since one of the cells contains an input box, we do not want new rows to be created as soon as the user starts typing in the textbox. So we are excluding it using ( != "text"). Here’s the output after clicking on Row 1 and 4


Live Demo:

4 - Click on a Row and Retrieve Values of all Cells in that Row

If you want to retrieve the value of all the cells in a row that was clicked, use the following code:

$("#someTable tbody").on("click", "tr", function () {
    var rowinfo = $(this).closest('tr').find('td').map(function () {
        return $(this).text();

From the clicked tr element, we navigate up to the row via closest(), and then find the cell (td) using find(). The map() method is useful in getting the value of a collection of td’s. Since the return value is a jQuery object (which contains an array) we use get() on the result to work with the array.

join() is not a jQuery function but a regular Array.join(separator) JavaScript function that converts an array to a string, putting the separator between each element. If the separator is omitted, by default the array elements are separated with a comma, as in our case.

Save and browse the file in a browser. Open the browser console window and click on any row to view the values of all the cells in that row.


Live Demo:


5 - Click on a Cell to display its Column Header

In our previous example, we saw how to retrieve the values of all the cells of the row that was clicked. If you want to click a cell and retrieve the column header to which it belongs, use this code:

$('#someTable tbody').on('click', 'td', function () {
    var idx = $(this).index();
    var thd = $(this).closest('tbody')

We start by getting the zero-based position of the clicked ‘td’ element in the idx variable. Then navigate up to the tbody via closest(), get the immediately preceding sibling and find() the th. siblings of the clicked 'td' element. Then filter those siblings for 'th' elements and use eq() supplying it an index to match the ‘th’, with that of the cell that was clicked. The final step is to retrieve the text of that element using text(). Observe how we have chained multiple jQuery functions to achieve our requirement.

I clicked on a cell containing ‘Ram’, 26 and E345. Open the console window of your browser to see the output.


Live Demo:

If you liked this article, take a look at my jQuery book The Absolutely Awesome jQuery Cookbook which contains scores of practical jQuery/jQueryUI recipes you can use in your projects right away.

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on Google+
Further Reading - Articles You May Like!
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook

Page copy protected against web site content infringement 	by Copyscape

Feedback - Leave us some adulation, criticism and everything in between!