Reputation: 719
given the following:
<div ID="parent">
<div ID="child1">Children Stuff</div>
<div ID="child2">More Childish things</div>
</div>
<div ID="orphan">Whhhaa I want a mommy</div>
var p = document.getElementById("parent");
var c = document.getElementById("orphan");
p.appendChild(c);
var ch = p.childNodes;
var ln = p.children;
for(var i=0;i < ln.length; i++) {
console.log(ch[i]);
}
console.log(ln.length);
The console output provides:
<div ID="child1">Children Stuff</div>
<div ID="child2">More Childish things</div>
3
Here's where I am lost: I need to obtain information out of each child node (including the new child). Naturally I won't be simply outputting it to a console, I need to perform some logic on other DOM elements that share similar IDs as the children.
Why doesn't the element.childNodes; call pick up on the new child? Any help is appreciated.
The above is sample air-code so I apologize if the syntax is not 100%, but I'm hoping the point gets accross nonetheless.
Upvotes: 0
Views: 47
Reputation: 11290
It just works if you fix the typos and become consistent in using p.children
or p.childNodes
:
var p = document.getElementById("parent");
var c = document.getElementById("orphan");
p.appendChild(c);
var ch = p.children;
for(var i=0;i < ch.length; i++) {
console.log(ch[i]);
}
console.log(ch.length);
Upvotes: 0
Reputation: 29916
Because you mix childNodes and children. Try using only children:
var p = document.getElementById("parent");
var c = document.getElementById("orphan");
p.appendChild(c);
var ln = p.children;
for(var i=0;i < ln.length; i++) {
console.log(ln[i]);
}
console.log(ln.length);
<div ID="parent">
<div ID="child1">Children Stuff</div>
<div ID="child2">More Childish things</div>
</div>
<div ID="orphan">Whhhaa I want a mommy</div>
Upvotes: 1
Reputation: 136104
You're looping over ln.length
but reading ch
:
for(var i=0;i < ln.length; i++) {
console.log(ch[i]);
}
That gets confusing very quickly, as ln
has a length of 3 and contains the child elements. ch
has a length of 6 and contains all elements (including 3 text elements with just line feeds).
This is really easy to see if you just add 2 more console logs:
console.log('ch',ch);
console.log('ln',ln);
As here: https://jsfiddle.net/mqhevnsu/
Upvotes: 1