<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;
it outputs “undefined”.
The
valueproperty only exists for form elements. If you want to get the content of any other elements, you can either useinnerHTML[MDN] to get the content as HTML string, ortextContent[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.1indicates an element node,3a text node: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.