获取小孩的值< div>的父< div> [英] get value of child <div> of a parent <div>
问题描述
<div id="parent">
<div id="child">
some-value
</div>
</div>
如何获得某些价值?
我试过
how do I get "some-value"? I tried
var parent = document.getElementById("parent");
var child = parent.childNodes[0];
var childval = child.value;
document.getElementById("output").innerHTML=childval;
它输出undefined。
it outputs "undefined".
推荐答案
c 属性仅存在于表单元素。如果您想获取任何其他元素的内容,您可以使用 innerHTML
[MDN] 将内容作为HTML字符串,或 textContent
[MDN] 或 innerText
[MSDN] 仅获取没有HTML标签的文本内容。
The value
property only exists for form elements. If you want to get the content of any other elements, you can either use innerHTML
[MDN] to get the content as HTML string, or textContent
[MDN] resp. innerText
[MSDN] to only get the text content without HTML tags.
childNodes
[MDN] 返回所有子节点,不仅是元素节点。这意味着,它也包含例如文本节点。在< div id =parent>
之后的换行符也是一个文本节点。因此, parent.childNodes [0]
返回只包含换行符的文本节点。
childNodes
[MDN] returns all child nodes, not only element nodes. That means, it also contains text nodes for example. The line break you have after <div id="parent">
is a text node as well. Hence, parent.childNodes[0]
returns the text node which consists only of a line break.
如果你要获取第一个元素节点,您可以使用 children
[MDN] (请参阅浏览器兼容性),或者遍历子节点,测试它们各自的节点类型。 1
表示一个元素节点, 3
一个文本节点:
If you want to get the first element node, you can either use children
[MDN] (see browser compatibility), or iterate over the child nodes, testing what kind of node each of them is. 1
indicates an element node, 3
a text node:
var child = parent.firstChild;
while(child && child.nodeType !== 1) {
child = child.nextSibling;
}
还有其他方法来检索元素,例如 getElementsByTagName
[MDN] 。
There are also other ways to retrieve elements, e.g. with getElementsByTagName
[MDN].
或者在你的情况下,你可以使用 getElementById
[MDN] 以获得对元素。
Or in your case, you can just use getElementById
[MDN] to get a reference to both of the elements.
这篇关于获取小孩的值< div>的父< div>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!