| re: innerHTML and tables...
Csaba Gabor wrote:[color=blue]
> RobG wrote:
>[color=green]
>> oT.onclick = sayHi;
>> if ( b ) el.innerHTML += 'Here\'s some more text';[/color]
>
>
> When you do that el.innerHTML += ...
> you are not (just) adding to el, you are completely redefining it.
> That is, el.innerHTML += ... means:
> el.innerHTML = el.innerHTML + ...
> and if some property is not sitting in the innerHTML, when you redefine
> it (that is, a property of el or any of its sub elements), by means of
> setting its innerHTML), it's gone.
>
> To that end, it may be instructive to actually see what that innerHTML
> is. Redefine your oT.onclick like so:
>
> oT.onclick = function(el) {return function() {
> alert('Hi from ' + this.nodeName + "\n" + el.innerHTML); } } (el);[/color]
It appears to be that when you add an onclick event to any element using
DOM, it is not added to its innerHTML. When you modify the innerHTML of
the element's parent, the element is written out again, without the
onclick attribute (this seems to be consistent for any intrinsic event)
effectively removing it.
While I originally thought it only happened with tables, with further
testing it appears that the same thing happens with other elements too -
intrinsic events are not included in the innerHTML if they aren't in the
original HTML source and have been added using some other method.
It does not seem to happen with other element attributes - style, id,
name, etc. nor does it happen if you modify the innerHTML of the element
itself, nor if you add the event using innerHTML (I guess that's
obvious, but...).
It's just a gotcha with innerHTML that I was not aware of before.
I can only guess that dynamically attached events are not included in an
elements' innerHTML because they may be added using a number of methods
and that some may be anonymous functions. But in that case I would have
thought that the function body would become the onclick attribute:
script: oT.onclick = function() { alert('hi'); };
==> innerHTML: ... onclick="alert('hi');" ...
and so on. Is this why the W3C has not added an innerHTML-type method
to the DOM?
--
Rob |