[英]javascript parent of parent
In javascript is there an easy way to target the parent of a parent? 在javascript中是否有一种简单的方法来定位父母的父母?
I'm using this.parentNode
as the element of a function to select the parent, and I tried both this.parent.parentNode
and this.parentNode.parentNode
, but both simply return the direct parent. 我使用
this.parentNode
作为选择父节点的函数的元素,我尝试了this.parent.parentNode
和this.parentNode.parentNode
,但两者this.parentNode.parentNode
返回直接父节点。
I'm trying to affect the div surrounding the div surrounding the 'this'. 我试图影响围绕'this'的div周围的div。 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.
我确实设法使用一个简单的循环语句使其工作,该语句重复两次parentNode选择,但我认为有更好的方法。
this.parentNode.parentNode
is 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.