System.InvalidCastException on a valid IHTMLDOMNode object?

I am working with an IE toolbar written using the .NET framework 2.0. Part of this toolbar is a section that works with the DOM directly. The section in question finds all the <object> tags in a web page and wraps them in a containing <div> tag. This is accomplished by creating the <div>, appending it to the object's parent, removing the object from the parent and appending it to the wrapping <div>:

privatevoid wrapObject(IHTMLElement element)

{

IHTMLElement wrapdiv = doc.createElement("div");

wrapdiv.style.height = element.offsetHeight;

wrapdiv.style.width = element.offsetWidth;

wrapdiv.id ="wrapdiv";

IHTMLDOMNode parent = ((IHTMLDOMNode)element).parentNode;

parent.appendChild((IHTMLDOMNode)wrapdiv);

parent.removeChild((IHTMLDOMNode)element);

((IHTMLDOMNode)wrapdiv).appendChild((IHTMLDOMNode)element);

}

The code seemed to work fine until we ran into a scenario where the <object> tag is contained inside of a <td> element:

************** Exception Text **************
System.InvalidCastException: Specified cast is not valid.
at mshtml.HTMLTableCellClass.IHTMLDOMNode_removeChild(IHTMLDOMNode oldChild)
at HT.Gadgets.Toolbar.GadgetToolbar.wrapObject(IHTMLElement element)

It is blowing up on the "removeChild" line, where the "element" is an HTMLObjectElement, which (according to the API) supports the IHTMLDOMNode interface just fine. There are other scenarios where wrapping the object tag in this manner works just fine, but in this particular instance I can not figure out why it is exploding.

Any thoughts?

[2415 byte] By [ArtieSluka] at [2008-1-12]