最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - reliabilty of 'isConnected' field in dom node - Stack Overflow

programmeradmin1浏览0评论

domNode.isConnected is a flag which is available in chrome. It shows whether domNode is part of the document.
Is it cross browser patible?
If not is there any efficient alternative for this for other browsers? Please provide link for any available documentation.

domNode.isConnected is a flag which is available in chrome. It shows whether domNode is part of the document.
Is it cross browser patible?
If not is there any efficient alternative for this for other browsers? Please provide link for any available documentation.

Share Improve this question edited Jun 2, 2016 at 10:17 rishabh dev asked Jun 2, 2016 at 9:49 rishabh devrishabh dev 1,7431 gold badge16 silver badges27 bronze badges 3
  • 1 This sounds a little like an X/Y problem. Could you describe why you need to know whether an element is already part of the DOM, as there may be a better way to achieve what you need. – Rory McCrossan Commented Jun 2, 2016 at 10:00
  • There are various ways to know if a node is part of the dom. But this I found most efficient as it requires no traversal. I just want know more about this and I cant find any thing about it anywhere. – rishabh dev Commented Jun 2, 2016 at 10:03
  • 1 Brief but docs here - dom.spec.whatwg/#dom-node-isconnected – Praveen Puglia Commented Jun 2, 2016 at 10:20
Add a ment  | 

3 Answers 3

Reset to default 9

It is not supported, but very easy to polyfill.

(function (supported){
  if (supported) return;
  Object.defineProperty(window.Node.prototype, 'isConnected', {get})
  function get() {
    return document.contains(this);
  }
})('isConnected' in window.Node.prototype);

A quick test shows Firefox doesn't support this property. So the answer is no.

var input = document.getElementById('input');
alert(input.isConnected);
<input type="text" id="input">

https://jsfiddle/hu08awn0/

This is a full node.isConnected polyfill that I wrote for IE & EdgeHTML:

if (!('isConnected' in Node.prototype)) {
  Object.defineProperty(Node.prototype, 'isConnected', {
    get() {
      return (
        !this.ownerDocument ||
        !(
          this.ownerDocument.pareDocumentPosition(this) &
          this.DOCUMENT_POSITION_DISCONNECTED
        )
      );
    },
  });
}
发布评论

评论列表(0)

  1. 暂无评论