Updated to properly handle HTMLElements and circular references