Javascript Get Child Nodes Of A Div
HTML code: How can I access the id='body' eleme
Solution 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';
}
Solution 2:
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 ...
}
Solution 3:
To get child nodes of a div, use:
var childNodes = parent.childNodes;
Or
var { childNodes } = parent;
Post a Comment for "Javascript Get Child Nodes Of A Div"