<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 child DIV needs to be the same width as the browser viewport. The child DIV must stay as a child of the parent div.
Set the position of div at the bottom of its container can be done using bottom, and position property. Set position value to absolute and bottom value to zero to placed a div at the bottom of container.
To check if an HTML element has child nodes, you can use the hasChildNodes() method. This method returns true if the specified node has any child nodes, otherwise false .
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.
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()
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With