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];
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];
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';
}
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 ...
}
To get child nodes of a div, use:
var childNodes = parent.childNodes;
Or
var { childNodes } = parent;