DOM parentNode和parentElement之间的区别

sha*_*unc 450 javascript firefox dom

有人可以用尽可能简单的方式解释我,经典DOM parentNode和Firefox 9中新引入的内容有什么区别parentElement

lon*_*day 436

parentElement 它是Firefox 9和DOM4的新功能,但它已经存在于所有其他主流浏览器中.

在大多数情况下,它是相同的parentNode.唯一的区别在于节点parentNode不是元素.如果是的话,parentElementnull.

举个例子:

document.body.parentNode; // the <html> element
document.body.parentElement; // the <html> element

document.documentElement.parentNode; // the document node
document.documentElement.parentElement; // null

(document.documentElement.parentNode === document);  // true
(document.documentElement.parentElement === document);  // false
Run Code Online (Sandbox Code Playgroud)

由于<html>element(document.documentElement)没有父元素,因此parentElementnull.(还有其他的,更不可能的情况parentElement可能null,但你可能永远不会遇到它们.)

  • 换句话说,它在99.999999999999%的时间内完全没有意义.是谁的想法? (144认同)
  • 原始的[`parentElement`](http://msdn.microsoft.com/en-us/library/ms534327(v = vs.85).aspx)是IE专有的东西; 我相信其他浏览器(例如Netscape)支持`parentNode`而不支持`parentElement`.(显然,鉴于我已经提到Netscape,我正在谈论回到IE5及更早的方式......) (23认同)
  • 正如我刚刚发现的那样,在一个SVG元素(如`g`中的`circle`)中,在IE中,`parentElement`将是未定义的,`parentNode`将是你正在寻找的东西.:( (12认同)
  • @lonesomeday你忘记了`documentfragment.firstChild.parentElement === null` (8认同)
  • @Raynos这实际上是我在回答的最后一句时所记得的确切情况...... (5认同)
  • 我以为你在想一些晦涩的东西,比如你在一个节点上有一个句柄,它的父节点是一个 ProcessingInstruction :D (2认同)
  • @JasonWalton我刚刚发现了这个并且有一个快速谷歌,看看我是否能找到理由.我找不到理由,但很高兴知道我并不孤单...... (2认同)
  • parentElement === null 非常有用 (2认同)

spe*_*ane 87

在Internet Explorer中,parentElement未定义SVG元素,而已parentNode定义.

  • 可能,但这就是我把头撞到桌子上一小时或更长时间的原因,直到我弄清楚了.我怀疑很多其他人在遭遇类似的头撞之后来到这个页面. (37认同)
  • 老实说,我认为这更多的是评论而不是答案. (10认同)
  • @speedplane很高兴这是一个答案,因为这没有任何逻辑意义,让我难以忍受... (3认同)
  • 它对于注释节点也未定义。在 Chrome 中,我很高兴得到评论的父级,但在 IE 中它是未定义的。 (2认同)

Pac*_*ier 11

使用.parentElement,只要您不使用文档片段,就不会出错.

如果您使用文档片段,则需要.parentNode:

let div = document.createDocumentFragment().appendChild(document.createElement('div'));
div.parentElement // null
div.parentNode // document fragment
Run Code Online (Sandbox Code Playgroud)

也:

let div = document.getElementById('t').content.firstChild
div.parentElement // null
div.parentNode // document fragment
Run Code Online (Sandbox Code Playgroud)
<template id="t"><div></div></template>
Run Code Online (Sandbox Code Playgroud)


显然是文档<html>.parentNode链接.这应该被认为是决定phail的文件是不是因为节点的节点被定义为通过文件和文件中可容纳不能通过文件包含.


Buk*_*ksy 10

就像nextSibling 和 nextElementSibling 一样,请记住,名称中带有“element”的属性总是返回Elementor null。没有的属性可以返回任何其他类型的节点。

console.log(document.body.parentNode, "is body's parent node");    // returns <html>
console.log(document.body.parentElement, "is body's parent element"); // returns <html>

var html = document.body.parentElement;
console.log(html.parentNode, "is html's parent node"); // returns document
console.log(html.parentElement, "is html's parent element"); // returns null
Run Code Online (Sandbox Code Playgroud)

  • 是的,但与 nextsibling 文本或注释节点不同,它不能是父节点。 (3认同)