I currently use this function to add tooltips to each table cell according to their row name (left-most cell in the row) and column name (value of top-most cell in the column). It works as intended, but it used up a significant amount of scripting time according to Google Chrome DevTools. How do I speed it up?
const add_tooltip = function(context) {
context.find("th").each(function() {
$(this).attr("title", $(this).text());
});
context.find("td").each(function() {
$(this).attr("title", $(this).siblings("th").text() + ", " + context.find("thead th").eq($(this).index()).text());
});
};
add_tooltip($("table"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>0</th>
<th>1</th>
<th>2</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<td>test</td>
<td>test</td>
</tr>
<tr>
<th>2</th>
<td>test</td>
<td>test</td>
</tr>
</tbody>
</table>
This is the new function I've come up with after collecting everyone's feedback. I've tested it and it doesn't seem much slower than including the title
attribute while constructing the table with $.append()
(which makes the code quite clunky).
const add_tooltip = function (context) {
let row_names = [], column_names = [];
context.find("th").each(function () {
$(this).attr("title", $(this).text());
if ($(this).parents("thead").length)
column_names.push($(this).text());
else
row_names.push($(this).text());
});
context.find("tbody, tfoot").find("tr").each(function (i) {
$(this).find("td").each(function (j) {
$(this).attr("title", `${row_names[i]}, ${column_names[j + 1]}`);
});
});
};