0

HTML code:

<div id="section">
  <div id="title" onclick="hideBody()"></div>
  <div id="body"></div>
</div>

How can I access the id="body" element using this....?
EXAMPLE:
this.parent.child[1];

Xriuk
  • 382
  • 2
  • 7
  • 26

3 Answers3

1

You can use nextElementSibling.

Example:

function hideBody(el) {
    'use strict';
    var sibling = el.nextElementSibling;
    console.log(sibling);

    sibling.style.visibility = 'hidden';
}

See jsFiddle.

As to answer your original question about child nodes, there is a childNodes property. For instance:

var children = document.getElementById('section').childNodes;

Relative to "this" (shown in the hideBody function):

function hideBody(el) {
    'use strict';
    var children = el.parentNode.childNodes;
    console.log(children);

    children[1].style.visibility = 'hidden';
}
rink.attendant.6
  • 44,500
  • 61
  • 101
  • 156
0

I'm not sure using 'this' is appropriate here, but you can certainly pass the event and grab the click target's ID:

http://jsfiddle.net/isherwood/6k7fc/

<div id="title" onclick="hideBody(event)"></div>

function hideBody(event) {
    var myId = event.target.id;
    var myEl = document.getElementById(myId);
    ... do stuff with myEl ...
}
isherwood
  • 58,414
  • 16
  • 114
  • 157
0

To get child nodes of a div, use:

var childNodes = parent.childNodes;

Or

var { childNodes } = parent;
yaya
  • 7,675
  • 1
  • 39
  • 38