Monday, July 21, 2008

The cloneNode Problem

This is the first entry into the foray of problems that I found when trying to create cross-browser compatible javascript. As I mentioned before, a client of mine is converting their web site from Internet Explorer(IE) to a fully cross-browser compatible web site. That includes IE6 (uggg), IE7, Firefox 3.0, and Safari 3.1.

So anyway, the cloneNode problem. Here's the issue. I needed to replace the IE specific outerHTML function (which I'll discuss in another blog) with a cross-browser version. It turned out that the cloneNode function would make it very easy to do that. The problem was, in very specific cases (i.e. my case), it didn't exactly clone everything. You see, there's a bug (suprise), that appears to be in IE, in which when you make dynamic modifications to the HTML before calling cloneNode, it doesn't clone the node exactly. It just sort of copies most of it..... Blah. Well, here's some example code for you to try for yourself:

<html>
<head>
<title>Javascript Today - cloneNode bug</title>
<script>
function runit()
{
var node = document.getElementById("checkbox");
node.checked = true;
var wrapper = document.getElementById("wrapper");
alert(wrapper.innerHTML);
var cloned = wrapper.cloneNode(true);
alert(cloned.innerHTML);
}
</script>
</head>
<body id="bod">
<div id="wrapper">
<input id="checkbox" type="checkbox">
<a href="javascript:runit();">Click Me to See Bug</a>
</div>
</body>
</html>

Note that the code that is displayed in the alert is different each time. Perhaps there is an easy workaround. In a lot of cases the cloneNode function works soundly but don't depend on it. If you are only planning on using the innerHTML property then you may want to just take the innerHTML and assign it to the innerHTML of another element. In a future blog, I will show you how I duplicated the IE specific outerHTML function in a cross-browser manner. Hope this helps and talk to you later.

2 comments:

Anonymous said...

>> In a future blog, I will show you how I duplicated
>> the IE specific outerHTML function in a cross-
>> browser manner.

????

MikeGuy said...

Well, the truth is, I started using jQuery which solved literally most my problems.