简体   繁体   English

如何在JavaScript中访问父元素的子元素

[英]How to access children of parent element in JavaScript

Naturally I tried: 我自然地尝试了:

function show() {
   this.parent.childNodes[1].childNodes[1].visibility = 'hidden';
}

But debugger says that parent has no property children. 但是调试器说父对象没有属性子对象。 What I'm doing wrong guys? 我在做错人吗? And I can't use jQuery, I'm on hosted webserver. 而且我不能使用jQuery,我在托管的Web服务器上。

You need to use parentNode for raw javascript, .parent() is jquery. 您需要对原始JavaScript使用parentNode,.parent()是jquery。 So in your case: 因此,在您的情况下:

function show() {
   this.parentNode.childNodes[1].childNodes[1].visibility = 'hidden';
}

Well, I got hasty with this one. 好吧,我对此很仓促。 Parent was not node element, so it had no children. 父级不是节点元素,因此没有子级。 And 'this' had no parentNode property. 而且“ this”没有parentNode属性。 What works is: 起作用的是:

function show(node) {
    node.parentNode.childNodes[1].childNodes[1].style.visibility = 'hidden';
}

and

<a class="hider" onclick="show(this)">Test</a>

Naturally to other people indexes in childNodes list are irrelevant. 自然地,其他人在childNodes列表中的索引是无关紧要的。 But for me they work, but certainly it is not cleaver on nice solution. 但是对我来说,它们是可行的,但肯定不是用好的解决方案来解决的。

Your 'this' seems to be the global scope. 您的“这”似乎是全球范围。 So 'this' points to window, which has no parent node. 因此,“此”指向没有父节点的窗口。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM