Skip to content

Instantly share code, notes, and snippets.

@eligrey
Last active December 26, 2022 01:09
Embed
What would you like to do?
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
)
);
},
});
}
@eligrey
Copy link
Author

eligrey commented Apr 12, 2021

@redfellow Thanks for pointing that out. This polyfill only works for EdgeHTML (Edge <= 18, pre-Edgium)

@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)

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