Javascript:如何判断节点对象是否已插入到文档/其他元素中

tho*_*ter 12 javascript internet-explorer dom

我希望能够识别给定的DOM节点是否已经附加/插入到另一个节点,或者它是否是document.createElement()或类似的新节点,并且没有被放置在任何地方.

在大多数浏览器中,只需检查parentNode即可.

if (!node.parentNode) {
  // this node is not part of a larger document
}
Run Code Online (Sandbox Code Playgroud)

但是,在Internet Explorer中,似乎新元素,即使在使用document.createElement()创建后,也已经有了一个parentNode对象(类型为DispHTMLDocument ??).

还有其他很好的跨浏览器和可靠的方式吗?

编辑:看起来Internet Explorer隐式创建DocumentFragment(nodeType为11)并将其设置为节点的parentNode属性.

nic*_*ckf 6

我认为,即使没有IE的弱点,检查parentNode的存在可能还不够.例如:

var d = document.createElement('div');
var s = document.createElement('span');
d.appendChild(s);
if (s.parentNode) {
    // this will run though it's not in the document
}
Run Code Online (Sandbox Code Playgroud)

如果文档中有某些内容,那么最终它的一个祖先就是文档本身.试试这个,看看它是怎么回事:

function inDocument(node) {
    var curr = node;
    while (curr != null) {
        curr = curr.parentNode;
        if (curr == document) return true;
    }
    return false;
}

// usage: 
// if (inDocument(myNode)) { .. }
Run Code Online (Sandbox Code Playgroud)

如果您只想检查某个深度 - 也就是说,您知道新创建的元素不会嵌入IE的片段,请尝试以下方法:

function inDocument(node, depth) {
    depth = depth || 1000;
    var curr = node;
    while ((curr != document) && --depth) {
        curr = curr.parentNode;
        if (curr == null) return false;
    }
    return true;
}

inDocument(myNode, 2);  // check only up to two deep.
inDocument(myNode);     // check up to 1000 deep.
Run Code Online (Sandbox Code Playgroud)


tho*_*ter 5

我找到了自己问题的答案.抱歉! 我最近似乎做了很多.

文档片段的nodeType为11,并且永远不会插入到文档中,因此您可以像这样检查它:

if (!node.parentNode || node.parentNode.nodeType == 11) {
  // this node is floating free
}
Run Code Online (Sandbox Code Playgroud)

插入多个对等节点时,只需要一个Document片段.IE隐式为所有新创建的节点创建一个.无论如何检查nodeType为11工作.