101010110101
101010110101

Reputation: 2000

How to focus on row in HTML Table?

Is it possible to focus on a specific HTML table row/cell with the help of Javascript? For instance, if this row is after the browser fold then the browser would scroll down to the row upon focus.

I have some JS code that searches an HTML table for a user's string input. I would then like for this code to focus on this word if it is found (Safari/Chrome browsers).

var targetTable = document.getElementById("accountTable");

for (var rowIndex = 1 + searchStart; rowIndex < targetTable.rows.length; rowIndex++)
{
    var rowData = '';
    rowData = targetTable.rows.item(rowIndex).cells.item(0).textContent;
    if (rowData.indexOf(str) != -1)
    {
                //focus on the row?
    }
}

Upvotes: 0

Views: 6215

Answers (2)

101010110101
101010110101

Reputation: 2000

I was able to achieve this by using scrollIntoView().

Upvotes: 1

Kenneth
Kenneth

Reputation: 415

You could give each row a HTML ID (either dynamically or statically depending on your needs) which matches the content and then use URI fragments to focus on it. You could basically use your current code and use

location.hash = rowData;

If the content matches the user input. This would of course be cumbersome if you've got whole sentences in the row you want to focus on, but for a simple table, it would work.

Upvotes: 2

Related Questions