I have a large table currently consisting of 95x120=11400 TD's and would like to dynamically edit properties such as height and background-color for all the cells from a certain row or column, or even a bunch of rows/columns. I want to do this in order to make the user able to resize rows/columns among other things. What would be a good way of getting that done?
All the TD's in my table does by the way have unique class for row/col eg row1, row2, row3, col1, col2, col3 added dynamically while the table is built up though Javascript.
You can also do table.rows[0] which gives a array of all TDs in that row. Then loop through it and change as wanted
Pretty simple if all of your cells are labeled with the appropriate classes.
Say you want to change the width of a certain column.
Or if you want to change the width of a bunch of columns.
Similarly with
Or if you want to change the background color
When making changes to such a huge structure, it is a good idea to remove it from the document first, so that it only gets re-processed at the end, when you re-insert it.
So, assuming your table is in a variable named
table
, you would do this:This can be done really efficiently by modifying css-rules dynamically. It also makes a lot more sense storing common properties i.e. height for a row of cells in a rule rather than storing it all in each element. And it takes up less memory as well.
With a table-layout like the following:
We can do something like this:
I did a bit of benchmarking and unless I'm going wrong somewhere the difference is quite tremendous. But yeah, apart from the benchmark it really does a huge noticeable difference in the real use case.
Would results from this be misleading for some reason? In that case I can't quite see where I'm going wrong so I'd appreciate feedback. These are the results I get.
Time taken to complete:
Loop 1: This one uses a simple jquery class-selector $(".cell").height(h);
Loop 2: This one is same as above but uses $(".cell").css("height",h) instead. It's faster
Loop 3: Same as above but it removes the table from DOM before modifying, then re-appending it. Seems faster in Firefox at least
Loop 4: This one modifies the css-rules dynamically: