get value of child <div> of a parent <div>

Solution 1:

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.

Solution 2:

The problem is that parent <div> actuially has three children: a TextNode containing a new line after parent opening tag, the actual child <div> and yet another TextNode with newline after closing child tag. But hard-coding second item is a bad idea:

var parent = document.getElementById("parent");
console.info(parent.childNodes.length);
var child = parent.childNodes[1];
var childval = child.innerHTML;

I would suggest iterating over children and finding the actual child or using

parent.getElementsByTagName('div')

shorthand.

That's one of the reasons why people love jQuery so much:

$('#parent div').text()

Solution 3:

var parent = document.getElementById("parent");
var child = parent.children[0];
var childVal = child.innerHTML;
document.getElementById("output").innerHTML = childVal;

DEMO : http://jsfiddle.net/bcqVC/2/

Solution 4:

document.getElementById("output").innerHTML = document.getElementById("child").innerHTML;

This will solve your problem.

Using your way of approach try as shown below

var parent = document.getElementById("parent");
var child = parent.childNodes[0];

var childval = child.innerHTML;

document.getElementById("outPut").innerHTML=childval;

This will also solve your problem