Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
154
rated 0 times [  160] [ 6]  / answers: 1 / hits: 97598  / 13 Years ago, sat, january 7, 2012, 12:00:00
<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.


More From » dom

 Answers
247

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.


[#88177] Thursday, January 5, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maya

Total Points: 418
Total Questions: 116
Total Answers: 112

Location: Mauritania
Member since Sun, Oct 17, 2021
3 Years ago
maya questions
Sun, Jul 4, 21, 00:00, 3 Years ago
Tue, Dec 22, 20, 00:00, 4 Years ago
Fri, Nov 6, 20, 00:00, 4 Years ago
Wed, Jul 29, 20, 00:00, 4 Years ago
Tue, Apr 21, 20, 00:00, 4 Years ago
;