In JavaScript we can create element dynamically and append to
section in order to apply CSS rule for huge number of elem
Apart from some scoping issues (there might be more tables on the page...) there is nothing inherently wrong with this approach - the style
elements are there in the DOM to be edited as you see fit, the browsers are following standards by respecting it. In your test case, there's not really a valid other approach since indeed colgroup
has extremely messy support - there are 78 duplicate bugs on the subject in Bugzilla, and Mozilla has been refusing to implement it properly since the first related bug report in 1998.
The reason it's faster is simply one of overhead - once the complete DOM is assembled a relatively minor stylesheet can be applied in native C++ much faster than a Javascript interpreter can ever loop over all rows and cells. This is because historically CSS rules are applied in reverse, and the browser keeps a dictionary inside quickly allowing it to find all td
elements. Native C++ will always beat more complex interpreter-based code.
In the future, the scoping issue can also be resolved with scoped styles (currently only in FF, rather typical), you'd be coding like this:
...
The scoped
attribute makes the contained styles only valid for its containing element, the table
in this case, and of course all its contained elements. And since you can access it by ID the contents are easily replaced/reconstructed.
While this would be preferable to your approach, as long as there's no universal browser support for this creating style
elements in the head
is the best workaround.