-
-
Save eligrey/f109a6d0bf4efe3461201c3d7b745e8f to your computer and use it in GitHub Desktop.
| /* | |
| * 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 | |
| ) | |
| ); | |
| }, | |
| }); | |
| } |
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? 🙂
@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.
Wouldn't a connected element always have a parentNode? (unless of course it's a root element)
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.
@redfellow Thanks for pointing that out. This polyfill only works for EdgeHTML (Edge <= 18, pre-Edgium)