Node.isConnected - Web APIs 编辑
The isConnected
read-only property of the Node
interface returns a boolean indicating whether the node is connected (directly or indirectly) to the context object, for example the Document
object in the case of the normal DOM, or the ShadowRoot
in the case of a shadow DOM.
Syntax
var isItConnected = nodeObjectInstance.isConnected
Return value
A Boolean
that is true
if the node is connected to its relevant context object, and false
if not.
Examples
Standard DOM
A standard DOM example:
let test = document.createElement('p');
console.log(test.isConnected); // Returns false
document.body.appendChild(test);
console.log(test.isConnected); // Returns true
Shadow DOM
A shadow DOM example:
// Create a shadow root
var shadow = this.attachShadow({mode: 'open'});
// Create some CSS to apply to the shadow dom
var style = document.createElement('style');
console.log(style.isConnected); // returns false
style.textContent = `
.wrapper {
position: relative;
}
.info {
font-size: 0.8rem;
width: 200px;
display: inline-block;
border: 1px solid black;
padding: 10px;
background: white;
border-radius: 10px;
opacity: 0;
transition: 0.6s all;
positions: absolute;
bottom: 20px;
left: 10px;
z-index: 3
}
`;
// Attach the created style element to the shadow dom
shadow.appendChild(style);
console.log(style.isConnected); // Returns true
Polyfill
Node.isConnected can be polyfilled with the following code for IE10 and EdgeHTML:
/* * Node.isConnected polyfill for IE and EdgeHTML * 2020-02-04 * * 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 ) ); }, }); }
Specifications
Specification | Status | Comment |
---|---|---|
DOM The definition of 'isConnected' in that specification. | Living Standard | Initial definition. |
Browser compatibility
BCD tables only load in the browser
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论