How to traverse childNode.length

How to traverse childNode.length
0

I’m trying understand childNodes and trying to traverse the childNode.length, but when I log the function I just get the entire function written once more in console. But not the childNode length’s content. i.e [<p>,apple,</p>,<p>,orange,</p>]

HTML

        <div id="nodes">
            <p>apple</p>
            <p>orange</p>
        </div>

   <div id="listofnodes"></div>
   
   <script>
   
   const Childnodes = document.getElementById('nodes').childNodes;

function Childnodes_list(){
    let i = 0; 
    if (i <= childNodes.length, i++) {
       Childnodes[i]; 
       document.getElementById('listofnodes').innerHTML = (Childnodes[i]);
    }
}

console.log (Childnodes_list);

   </script>

@Jason109 You have several issues in the code posted.

  1. In your console.log statement you are just logging the function and not calling the function, so that is why you just see the function code displayed.

  2. You initialize a variable named Childnoes outside of the function (which is fine). but inside the if statement condition, you refer to a different spelling of the variable (JavaSrcript is case-sensitive).

  3. The line that just has Childnodes[i]; on it will not do anything at all, so you can delete that line.

  4. The childNodes property you are using in the initialization of the Childnodes variable contains a NodeList (similar to an array). However, it contains not just the p elements nested in the div with id=“nodes”. It also contains text nodes like the space before and after each p element. I recommend using the children property that will only be the two p elements.

  5. Your if statement has a comma and then i++ that does not belong there. If you are trying to iterate through the Childnodes, then you should probably use a for loop instead.

  6. Once you resolve the issues above, you will need to fix the following line:

document.getElementById('listofnodes').innerHTML = (Childnodes[i]);

Since Childnodes will be an array like object, you can not assign it to the innerHTML property, since it is not a string. You could however look into using the appendChild method here.

You have some other issues, but I will let you first sort the ones I have pointed out so far.

Thank you very much for the input, I think have a better grasp now.