ch****************@gmail.com wrote:
RobG wrote:
You are best to use innerHTML for very simple things like writing text
strings or simple markup. Use DOM methods for complex stuff.
What I'm actually doing is updating a calendar that pops up in an
iframe. There are "next month" and "previous month" buttons and when
the user clicks one of those the calendar should redraw itself with the
new month.
Now, I *could* go through each cell and change the contents with DOM
calls. But since this is just a very simple 7x4 table, I thought that
everything would look a lot cleaner if I just completely rewrote the
body.
But you're saying that's a bad idea?
My comment was in regard to using innerHTML to modify only part of a
table. Using innerHTML for rebuilding the entire calendar isn't so much
good or bad, but that there are better ways.
Browsers are optimised to parse and render HTML very quickly, so in
terms of speed, using innerHTML tends to be very fast. However, you
must first construct the HTML and the resources for that must also be
factored in.
I think it would be more efficient to build the table once using HTML,
then modify the text in the calendar cells for each change of month.
That could be done using innerHTML but probably more efficiently by
building the table once and subsequently modifying just the text nodes.
Consider creating an array of references to the text nodes for the date
cells, then just modify those. The table is built once only, as is the
array of references. You may also want to have different styles for
cells with dates, cells without and weekends.
You need a bigger table than 7x4 - some months may span up to 6 weeks
(e.g. a 31 day month starting on a Saturday). I built a calendar along
similar lines recently, I'll dig it out and post it if you like. It ran
virtually instantaneously even on very old machines.
The algorithm is simple - loop through the cell reference array blanking
cells until you get to the the day number of the first day of the month
(adjusting for Sunday or Monday as the first day of the week is simple).
Put dates starting from 1 in the following cells for each day of the
month until the last, then blank the remaining cells to the end. Often
you'll have a full row empty at the bottom - maybe you'll want to hide
the row in that case.
I can't imagine that the algorithm for creating the HTML would be
simpler, especially if the table also has labels for days, weeks, year,
month name, next/previous month/year buttons, changing styles for
weekends, etc.
--
Rob