javascript Javascript获取div的子节点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19500592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript get child nodes of a div
提问by Xriuk
HTML code:
HTML代码:
<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];
如何id="body"
使用this.
...访问元素?
例子:this.parent.child[1];
回答by rink.attendant.6
You can use nextElementSibling
.
您可以使用nextElementSibling
.
Example:
例子:
function hideBody(el) {
'use strict';
var sibling = el.nextElementSibling;
console.log(sibling);
sibling.style.visibility = 'hidden';
}
See jsFiddle.
参见jsFiddle。
As to answer your original question about child nodes, there is a childNodes
property. For instance:
为了回答您关于子节点的原始问题,有一个childNodes
属性。例如:
var children = document.getElementById('section').childNodes;
Relative to "this
" (shown in the hideBody function):
相对于“ this
”(显示在 hideBody 函数中):
function hideBody(el) {
'use strict';
var children = el.parentNode.childNodes;
console.log(children);
children[1].style.visibility = 'hidden';
}
回答by yaya
To get child nodes of a div, use:
要获取 div 的子节点,请使用:
var childNodes = parent.childNodes;
Or
或者
var { childNodes } = parent;
回答by isherwood
I'm not sure using 'this' is appropriate here, but you can certainly pass the event and grab the click target's ID:
我不确定在此处使用“this”是否合适,但您当然可以传递事件并获取点击目标的 ID:
http://jsfiddle.net/isherwood/6k7fc/
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 ...
}