获取父级
的子级
的值

2023-11-21

<div id="parent">
    <div id="child">
        some-value
    </div>
</div>

我如何获得“某些价值”? 我试过

var parent = document.getElementById("parent");
var child = parent.childNodes[0];
var childval = child.value;
document.getElementById("output").innerHTML=childval;

它输出“未定义”。


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] 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.

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;
}

There are also other ways to retrieve elements, e.g. with getElementsByTagName [MDN].

Or in your case, you can just use getElementById [MDN] to get a reference to both of the elements.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

获取父级
的子级
的值 的相关文章

随机推荐