Skip to content

Instantly share code, notes, and snippets.

@eligrey
Last active July 11, 2023 12:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eligrey/f109a6d0bf4efe3461201c3d7b745e8f to your computer and use it in GitHub Desktop.
Save eligrey/f109a6d0bf4efe3461201c3d7b745e8f to your computer and use it in GitHub Desktop.
Node.isConnected polyfill for EdgeHTML
/*
* Node.isConnected polyfill for EdgeHTML
* 2021-04-12
*
* By Eli Grey, https://eligrey.com
* Public domain.
* NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
*/
if (!('isConnected' in Node.prototype)) {
Object.defineProperty(Node.prototype, 'isConnected', {
get() {
return (
!this.ownerDocument ||
!(
this.ownerDocument.compareDocumentPosition(this) &
this.DOCUMENT_POSITION_DISCONNECTED
)
);
},
});
}
@mindplay-dk
Copy link

Isn't contains basically the opposite of isConnected?

This should be much simpler to polyfill - just grab the ownerDocument (which is available as soon as you call document.createElement - documents can own nodes before they actually get inserted) and see if it contains the element:

Object.defineProperty(Node.prototype, "isConnected", {
  get() {
    return this.ownerDocument.contains(this);
  }
});

Seems to work well enough? 🙂

@eligrey
Copy link
Author

eligrey commented Jun 15, 2022

@mindplay-dk Sorry, I missed your question. I think compareDocumentPosition() may be more efficient than contains(). I made this polyfill originally to be used in a performance-sensitive code path.

Also, ownerDocument can be null for some Nodes, e.g. document.ownerDocument === null (document is a Node), so your implementation would break in that case.

@vanowm
Copy link

vanowm commented Dec 26, 2022

Wouldn't a connected element always have a parentNode? (unless of course it's a root element)

@theseer
Copy link

theseer commented Jul 11, 2023

Wouldn't a connected element always have a parentNode? (unless of course it's a root element)

Depends on your definition of "connected". If it's a childnode within a subtree that's not connected, it does have a parentNode - but it's still not "connected" within the Document.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment