父级的 javascript 父级

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15367111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:32:55  来源:igfitidea点击:

javascript parent of parent

javascriptparent

提问by user2126833

In javascript is there an easy way to target the parent of a parent?

在 javascript 中是否有一种简单的方法来定位父级的父级?

I'm using this.parentNodeas the element of a function to select the parent, and I tried both this.parent.parentNodeand this.parentNode.parentNode, but both simply return the direct parent.
I'm trying to affect the div surrounding the div surrounding the 'this'. I did manage to make it work using a simple loop statement that repeats the parentNode selection twice, but I assume there's a better way.

this.parentNode用作函数的元素来选择父项,我尝试了两者this.parent.parentNodethis.parentNode.parentNode,但都只是返回直接父项。
我试图影响围绕“this”的 div 周围的 div。我确实设法使用一个简单的循环语句使其工作,该语句重复 parentNode 选择两次,但我认为有更好的方法。

回答by T.J. Crowder

this.parentNode.parentNodeis correct, you must (with apologies!) have had a mistake in the test where you tried it.

this.parentNode.parentNode是正确的,您必须(抱歉!)在您尝试的测试中出错。

Example: Live Copy| Source

示例:实时复制| 来源

HTML:

HTML:

<div id="outermost">Outermost
  <div id="inner1">Inner 1
    <div id="inner2">Inner 2</div>
  </div>
</div>

JavaScript:

JavaScript:

var inner2 = document.getElementById("inner2");

display("inner2.id = " + inner2.id);
display("inner2.parentNode.id = " + inner2.parentNode.id);
display("inner2.parentNode.parentNode.id = " + inner2.parentNode.parentNode.id);

display("Try clicking the blue 'inner2' above");

inner2.onclick = function(e) {
  display("Click: this.id = " + this.id);
  if (this.parentNode) {
    display("Click: this.parentNode.id = " + this.parentNode.id);
    if (this.parentNode.parentNode) {
      display("Click: this.parentNode.parentNode.id = " + this.parentNode.parentNode.id);
    }
  }
};

function display(msg) {
  var p = document.createElement('p');
  p.innerHTML = String(msg);
  document.body.appendChild(p);
}

Output (assuming one clicks as directed):

输出(假设按指示单击):

inner2.id = inner2
inner2.parentNode.id = inner1
inner2.parentNode.parentNode.id = outermost
Try clicking the blue 'inner2' above
Click: e.target.id = inner2
Click: e.target.parentNode.id = inner1
Click: e.target.parentNode.parentNode.id = outermost