IE and funkiness w/innerHTML property

Posted by Dan on Mar 26, 2003 @ 3:16 PM

Today I noticed a strange thing with Internet Explorer v6.x. It appears when using the innerHTML property to read the contents of an element, it must be doing some parsing to the entire DOM tree that the current element resides in. Here's how I noticed the problem.

First, it appeared that the larger the DOM tree was, the longer it took to recieve the value for an element. In my test loop, it took an average of 4 seconds to parse a table by looping through all the rows in the table retrieving the value of firstChild property for each cell. The speed increased dramatically to the range of about 36 seconds by just invoking the innerHMTL property instead of firstChild property.

Second, I noticed it would get faster as I removed elements from the table I was parsing. If I removed each row after processing the contents, it would get faster and faster as less elements where found in the DOM branch. I found this extremely odd and the combination of both points leads me to believe that retrieving the value of the innerHTML property of an element does more than just reads the value.

Unfortunately I really needed to use the innerHTML property, as I need to get to the value of each cell—including any HTML that resides in the cell.

Since it seemed the size of the DOM tree mattered, I figured I'd see what would happen if I made a clone of the element before reading the innerHTML property. Using the cloneNode(true) method before invoking the innerHTML property prooved to speed up the loop by about 300%.

So, instead of invoking:
  element.innerHTML;

I used:
  element.cloneNode(true).innerHTML;

NOTE:
Interestingly enough, it actually prooved to be slightly faster to clone the row instead of each cell individually. I assume this is because it was faster for the innerHTML property to do it's thing over a single row, than it was to actually use the cloneNode(true) on each cell.

There's definitely some expense to using the cloneNode() method, but in this case it definitely increased performance overall. I suspect you wouldn't want to do this in every case, and it may only help when looping through a large branch in the DOM. In any case, you may want to try this technique if you're trying to parse the contents of each cell in a table.

Categories: JavaScript

Comments for this entry have been disabled.