Piotr Kamoda
Piotr Kamoda

Reputation: 1006

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.

Upvotes: 0

Views: 2260

Answers (3)

Piotr Kamoda
Piotr Kamoda

Reputation: 1006

Well, I got hasty with this one. Parent was not node element, so it had no children. And 'this' had no parentNode property. 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. But for me they work, but certainly it is not cleaver on nice solution.

Upvotes: 1

adrield
adrield

Reputation: 625

Your 'this' seems to be the global scope. So 'this' points to window, which has no parent node.

Upvotes: 0

amespower
amespower

Reputation: 917

You need to use parentNode for raw javascript, .parent() is jquery. So in your case:

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

Upvotes: 1

Related Questions